在求LCA的方法上我选取了重链剖分,但是不知为何答案不对
求调
#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
int n,m,s,vistime;
int wc[N],sz[N],dep[N],top[N],fa[N];
vector<int> g[N];
void dfs1(int u,int f){
fa[u] = f;
dep[u] = dep[f] + 1;
sz[u] = 1;
for(auto v : g[u]){
if(v == f) continue;
dfs1(v,u);
sz[u] += sz[v];
if(sz[v] > sz[wc[u]]) wc[u] = v;
}
return;
}
void dfs2(int u,int Top){
top[u] = Top;
if(wc[u] != 0){
dfs2(wc[u],Top);
for(auto v : g[u]){
if(v != fa[u] && v != wc[u])
dfs2(v,v);
}
}
}
int qry(int x,int y){
while(top[x] != top[y]){
if(dep[top[x]] < dep[top[y]]) swap(x,y);
x = fa[top[x]];
}
return (dep[x] < dep[y]) ? x : y;
}
int main(){
ios:: sync_with_stdio(false);
cin >> n >> m >> s;
for(int i = 1; i < n; i ++){
int u,v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs1(s,0);
dfs2(s,0);
while(m --){
int x,y;
cin >> x >> y;
cout << qry(x,y) << endl;
}
return 0;
}