我想先用暴力跳试一下,但是不知为什么全RE,样例过了。经过我的多次提交,感觉是depth函数出了问题,请求解答
#include<bits/stdc++.h>
using namespace std;
int n, m, s;
vector<int>a[500010];
int d[500010];
int fa[500010];
bool vis[500010];
int depth(int s, int p){
d[s] = p;
vis[s] = 1;
for(int i=0;i<a[s].size();i++){
int to = a[s][i];
if(vis[to])continue;
fa[to] = s;
depth(to, p+1);
}
}
int LCA(int x, int y){
while(d[x] > d[y])x = fa[x];
while(d[x] < d[y])y = fa[y];
while(x != y)x = fa[x], y = fa[y];
return x;
}
int main(){
cin>>n>>m>>s;
for(int i=1;i<n;i++){
int u, v;
cin>>u>>v;
a[u].push_back(v);
a[v].push_back(u);
}
fa[s] = s;
depth(s, 1);
while(m--){
int x, y;
cin>>x>>y;
cout<<LCA(x, y)<<endl;
}
return 0;
}