求助
#include <bits/stdc++.h>
using namespace std;
int N, M, S;
const int MAXN(5e5 + 5), MAXM(MAXN + MAXN);
int head[MAXN], tot;
int fa[MAXN][30];
int dep[MAXN];
bool book[MAXN];
int rem[MAXN];
struct Arc {
int to, nex;
}arc[MAXM];
void Add(const int u, const int v) {
arc[++tot].nex = head[u];
head[u] = tot;
arc[tot].to = v;
}
void dfs(const int u, const int v, const int depth) {
dep[u] = depth;
fa[u][0] = v;
for (int i(head[u]); i; i = arc[i].nex) {
const int to(arc[i].to);
if (to != v) {
dfs(to, u, depth + 1);
}
}
}
int getFa(int u, int lev) {
for (int i(25); i >= 0; --i) {
const int t(1 << i);
while (lev >= t) {
lev -= t;
u = fa[u][i];
}
}
return u;
}
void Init() {
for (int k(1); k <= 25; ++k) {
for (int u(1); u <= N; ++u) {
int t(u);
for (int i(1); i <= 2; ++i) {
t = fa[t][k - 1];
}
fa[u][k] = t;
}
}
}
int getLCA(int a, int b) {
if (dep[a] <= dep[b]) {
swap(a, b);
}
a = getFa(a, dep[a] - dep[b]);
if (a == b) {
return a;
}
for (int i(25); i >0; --i) {
const int ta(getFa(a, i)), tb(getFa(b, i));
if (ta != tb) {
a = ta;
b = tb;
}
}
return fa[a][0];
}
int main() {
scanf("%d %d %d", &N, &M, &S);
for (int i(1); i < N; ++i) {
int u, v;
scanf("%d %d", &u, &v);
Add(u, v); Add(v, u);
}
dfs(S, 0, 0);
Init();
while (M--) {
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n", getLCA(a,b));
}
return 0;
}
wa了最后两个点 求助!