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
| #include <bits/stdc++.h> using namespace std;
struct Edge { int t,next; }Edge[2*500001]; int depth[500001],f[500001][22],log1[500001],head[500001]; int tot,n,m,s;
inline void addedge(int x,int y) { Edge[++tot].t=y; Edge[tot].next=head[x]; head[x]=tot; Edge[++tot].t=x; Edge[tot].next=head[y]; head[y]=tot; }
void dfs(int now,int last) { depth[now]=depth[last]+1; f[now][0]=last; for (int i=1;(1<<i)<=depth[now];i++) f[now][i]=f[f[now][i-1]][i-1]; for (int i=head[now]; i; i=Edge[i].next) if (Edge[i].t!=last) dfs(Edge[i].t,now); }
int LCA(int x,int y) { if (depth[x]<depth[y]) swap(x,y); while (depth[x]>depth[y]) x=f[x][log1[depth[x]-depth[y]]-1]; if (x==y) return x; for (int i=log1[depth[x]]-1;i>=0;i--) if (f[x][i]!=f[y][i]) x=f[x][i], y=f[y][i]; return f[x][0]; }
int main() { int x,y; scanf("%d%d",&n,&s); for (int i=1;i<n;i++) { scanf("%d%d",&x,&y); addedge(x,y); } dfs(s,0); for (int i=1;i<=n;i++) log1[i]=log1[i-1]+(1<<log1[i-1]==i); scanf("%d%d",&x,&y); printf("%d\n",LCA(x,y)); return 0; }
|