RT,我已经两个月没写代码,能力大大下降了,,,
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 10;
int n, m, s;
int fa[MAXN][30], d[MAXN];
struct edge {
int from, to;
edge(int x, int y) { from = x; to = y; }
};
vector<edge> e;
vector<int> G[MAXN];
void dfs(int x, int f) {
fa[x][0] = f; d[x] = d[f] + 1;
for (int i = 1; 1 << i <= d[x]; i++) {
fa[x][i] = fa[fa[x][i - 1]][i - 1];
}
for (int i = 0; i < G[x].size(); i++) {
if (e[G[x][i]].to != f)dfs(e[G[x][i]].to, x);
}
}
int LCA(int x, int y) {
if (d[x] < d[y])swap(x, y);
for (int i = 20; i >= 0; i--) {
if (d[x] - d[y] >= 1 << i)x = fa[x][i];
else break;
}
if (x == y)return x;
for (int i = 20; i >= 0; i--) {
if (fa[x][i] == fa[y][i])continue;
else {
x = fa[x][i]; y = fa[y][i];
}
}
return fa[x][0];
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m >> s;
int x, y;
for (int i = 0; i < n - 1; i++) {
cin >> x >> y;
e.push_back(edge(x, y));
G[x].push_back(e.size() - 1);
e.push_back(edge(y, x));
G[x].push_back(e.size() - 1);
}
dfs(s, 0);
for (int i = 0; i < m; i++) {
cin >> x >> y;
cout << LCA(x, y) << endl;
}
return 0;
}