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.
62 lines
1.2 KiB
62 lines
1.2 KiB
#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 fa[N];
|
|
|
|
void bfs(int root) {
|
|
queue<int> q;
|
|
q.push(root);
|
|
depth[root] = 1;
|
|
fa[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;
|
|
fa[v] = u;
|
|
q.push(v);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int lca(int a, int b) {
|
|
if (depth[a] > depth[b]) swap(a, b);
|
|
while (depth[a] < depth[b]) b = fa[b];
|
|
while (a != b) a = fa[a], b = fa[b];
|
|
return a;
|
|
}
|
|
int main() {
|
|
#ifndef ONLINE_JUDGE
|
|
freopen("P3379.in", "r", stdin);
|
|
#endif
|
|
memset(h, -1, sizeof h);
|
|
|
|
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;
|
|
} |