1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include<bits/stdc++.h> using namespace std; int N,M,S; struct edge{ int t,nx; } r[500002<<1]; int rf[500002],rcnt; void add(int a,int b){ rcnt++; r[rcnt].t=b; r[rcnt].nx=rf[a]; rf[a]=rcnt; return; } int lg[500002],depth[500002],fa[500002][22]; void dfs(int now,int fat){ fa[now][0]=fat; depth[now]=depth[fat]+1; for(int i=1;i<=lg[depth[now]];i++){ fa[now][i]=fa[fa[now][i-1]][i-1]; } int cnt=rf[now]; while(cnt>0){ if(r[cnt].t!=fat) dfs(r[cnt].t,now); cnt=r[cnt].nx; } return; } int lca(int a,int b){ if(depth[a]<depth[b]){ swap(a,b); } while(depth[a]>depth[b]){ a=fa[a][lg[depth[a]-depth[b]]]; } if(a==b){ return a; } for(int i=lg[depth[a]];i>=0;i--){ if(fa[a][i]!=fa[b][i]){ a=fa[a][i]; b=fa[b][i]; } } return fa[a][0]; } int main(){ cin>>N>>M>>S; for(int i=1;i<N;i++){ int x,y; cin>>x>>y; add(x,y); add(y,x); }
for(int i=1;i<=N;i++){ lg[i]=log2(i); }
dfs(S,0);
for(int i=1;i<=M;i++){ int x,y; cin>>x>>y; cout<<lca(x,y)<<endl; } return 0; }
|