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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<cstdlib> #include<algorithm> #include<ctime> #include<iomanip> #include<queue> #include<stack> #include<map> #include<vector> #define gh() getchar() #define re register #define db double typedef long long ll; using namespace std; const int MAXN=5e5+1; template<class T> inline void read(T &x) { x=0; char ch=gh(),t=0; while(ch<'0'||ch>'9') t|=ch=='-',ch=gh(); while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+(ch^48),ch=gh(); if(t) x=-x; } template<class T,class ...T1> inline void read(T &x,T1 &...x1) { read(x),read(x1...); } template<class T> inline bool checkMax(T &x,T &y) { return x<y?x=y,1:0; } template<class T> inline bool checkMin(T &x,T &y) { return x>y?x=y,1:0; } int N,M,Root; struct Graph { int next,to; Graph(int n=0,int t=0):next(n),to(t){} }Edge[MAXN<<1]; int Head[MAXN],Total; inline void addEdge(int u,int v) { Edge[++Total]=Graph(Head[u],v);Head[u]=Total; Edge[++Total]=Graph(Head[v],u);Head[v]=Total; } int Size[MAXN],Dep[MAXN],Top[MAXN],Fa[MAXN],Son[MAXN]; void dfsTree(int x,int last,int dep) { Fa[x]=last,Size[x]=1,Dep[x]=dep; for(int e=Head[x],v;e;e=Edge[e].next) { if((v=Edge[e].to)==last) continue; dfsTree(v,x,dep+1); Size[x]+=Size[v]; if(!Son[x]||Size[Son[x]]<Size[v]) Son[x]=v; } } void dfsDfn(int x,int topf) { Top[x]=topf; if(!Son[x]) return ; dfsDfn(Son[x],topf); for(int e=Head[x],v;e;e=Edge[e].next) { v=Edge[e].to; if(v==Fa[x]||v==Son[x]) continue; dfsDfn(v,v); } } inline int lca(int x,int y) { while(Top[x]!=Top[y]) { if(Dep[Top[x]]<Dep[Top[y]]) swap(x,y); x=Fa[Top[x]]; } if(Dep[x]>Dep[y]) swap(x,y); return x; } int main() { read(N,M,Root); for(int i=2,u,v;i<=N;++i) { read(u,v); addEdge(u,v); } dfsTree(Root,0,1); dfsDfn(Root,Root); for(int i=1,x,y;i<=M;++i) { read(x,y); printf("%d\n",lca(x,y)); } return 0; }
|