You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
using namespace std;
|
|
|
|
|
const int N = 500010, M = N << 1;
|
|
|
|
|
|
|
|
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
|
|
|
void add(int a, int b, int c = 0) {
|
|
|
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int depth[N];
|
|
|
|
|
int f[N][20];
|
|
|
|
|
|
|
|
|
|
void bfs(int root) {
|
|
|
|
|
queue<int> q;
|
|
|
|
|
q.push(root);
|
|
|
|
|
depth[root] = 1;
|
|
|
|
|
while (q.size()) {
|
|
|
|
|
int u = q.front();
|
|
|
|
|
q.pop();
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
|
int v = e[i];
|
|
|
|
|
if (!depth[v]) {
|
|
|
|
|
depth[v] = depth[u] + 1;
|
|
|
|
|
f[v][0] = u;
|
|
|
|
|
q.push(v);
|
|
|
|
|
|
|
|
|
|
for (int k = 1; k <= 19; k++) f[v][k] = f[f[v][k - 1]][k - 1];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int lca(int a, int b) {
|
|
|
|
|
if (depth[a] < depth[b]) swap(a, b);
|
|
|
|
|
|
|
|
|
|
for (int k = 19; k >= 0; k--)
|
|
|
|
|
if (depth[f[a][k]] >= depth[b]) a = f[a][k];
|
|
|
|
|
|
|
|
|
|
if (a == b) return a;
|
|
|
|
|
|
|
|
|
|
for (int k = 19; k >= 0; k--)
|
|
|
|
|
if (f[a][k] != f[b][k])
|
|
|
|
|
a = f[a][k], b = f[b][k];
|
|
|
|
|
|
|
|
|
|
return f[a][0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
#ifndef ONLINE_JUDGE
|
|
|
|
|
freopen("P3379.in", "r", stdin);
|
|
|
|
|
#endif
|
|
|
|
|
memset(h, -1, sizeof h);
|
|
|
|
|
|
|
|
|
|
// Q:为什么上面的数组开20,每次k循环到19?
|
|
|
|
|
// 答: cout << log2(500000) << endl;
|
|
|
|
|
|
|
|
|
|
int n, m, s;
|
|
|
|
|
scanf("%d %d %d", &n, &m, &s);
|
|
|
|
|
|
|
|
|
|
int a, b;
|
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
|
scanf("%d %d", &a, &b);
|
|
|
|
|
add(a, b), add(b, a);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bfs(s);
|
|
|
|
|
|
|
|
|
|
while (m--) {
|
|
|
|
|
scanf("%d %d", &a, &b);
|
|
|
|
|
cout << lca(a, b) << endl;
|
|
|
|
|
}
|
|
|
|
|
return 0;
|
|
|
|
|
}
|