|
- #include<iostream>
- #include<cstdio>
- using namespace std;
- #define FOR(i,a,b) for(int i=a;i<=b;i++)
- #define For(i,a,b) for(int i=a;i>=b;i--)
- const int MX=500010;
- int first[MX],next[MX*2],dep[MX],f[MX][25];
- int uu[MX*2],vv[MX*2],fath[MX],n,root,t,tt,m,la;
- int getint()
- {
- int w = 0, q = 0;
- char c = getchar();
- while ((c < '0' || c > '9') && c != '-') c = getchar();
- if (c == '-') q = 1, c = getchar();
- while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar();
- return q ? -w : w;
- }
- void scan()
- {
- scanf("%d %d %d",&n,&m,&root);
- FOR(i,1,n-1)
- {
- uu[i]=getint();
- vv[i]=getint();
- uu[i+n]=vv[i];
- vv[i+n]=uu[i];
- }
- FOR(i,1,2*n)
- {
- next[i]=first[uu[i]];
- first[uu[i]]=i;
- }
- }
- void pre(int u,int fa)
- {
- dep[u]=dep[fa]+1;
- FOR(i,1,20) f[u][i]=f[f[u][i-1]][i-1];
- for(int i=first[u];i!=0;i=next[i])
- {
- if(vv[i]==fa) continue;
- f[vv[i]][0]=uu[i];
- pre(vv[i],uu[i]);
- }
- }
- int lca(int x,int y)
- {
- if(x==y) return x;
- if(dep[x]<dep[y]) swap(x,y);
- For(i,20,0)
- {
- if(dep[f[x][i]]>=dep[y]) x=f[x][i];
- if(dep[x]==dep[y]) break;
- }
- if(x==y) return x;
- For(i,20,0)
- if(f[x][i]!=f[y][i])
- {
- x=f[x][i];
- y=f[y][i];
- }
- return f[x][0];
- }
- int main()
- {
- scan();pre(root,0);
- FOR(kk,1,m)
- {
- t=getint();
- tt=getint();
- printf("%d\n",lca(t,tt));
- }
- return 0;
- }
复制代码 |
|