Although very basic, but still review a bit, after all, than the tree is well-written ...
Code:
#include <iostream>#include<cstdio>#include<cmath>#include<ctime>#include<queue>#include<algorithm>#include<cstring>using namespacestd;#defineDuke (I,a,n) for (int i = a;i <= n;i++)#defineLV (i,a,n) for (int i = a;i >= n;i--)#defineClean (a) memset (A,0,sizeof (a))Const intINF =1<< -;Const intN =300005; typedefLong LongLl;typedefDoubledb;template<classT>voidRead (T &x) { CharC; BOOLOP =0; while(c = GetChar (), C <'0'|| C >'9') if(c = ='-') op =1; X= C-'0'; while(c = GetChar (), C >='0'&& C <='9') x= x *Ten+ C-'0'; if(OP) x =-x;} Template<classT>voidwrite (T x) {if(X <0) Putchar ('-'), x =-x; if(x >=Ten) Write (X/Ten); Putchar ('0'+ x%Ten);}structnode{intL,R,NXT;} a[1001000];intn,m,s;intlst[500100],len =0;voidAddintXinty) {a[++LEN].L =x; A[LEN].R=y; A[LEN].NXT=Lst[x]; LST[X]=Len;}intst[500010][ +];intdep[500010];voidDfsintUintFaintdepth) {Dep[u]=depth; st[u][0] =FA; for(inti =1;(1<< i) <= dep[u];i++) {St[u][i]= St[st[u][i-1]][i-1]; } for(intK = Lst[u];k;k =a[k].nxt) { inty =A[K].R; if(y = = FA)Continue; DFS (y,u,depth+1); }}intLcaintXinty) { if(Dep[x] >Dep[y]) swap (x, y); intCH = dep[y]-Dep[x]; Duke (I,0, in) { if(Ch & (1<<i)) y=St[y][i]; } if(x = =y)returnx; LV (i, in,0) { if(St[x][i]! =St[y][i]) {x=St[x][i]; Y=St[y][i]; }} x= st[x][0]; returnx;}intMain () {read (n); read (m); Read (s); Duke (I,1N1) { intx, y; Read (x); Read (y); Add (x, y); Add (y,x); } DFS (S,0,0); intg,h; Duke (I,1, M) {Read (g); Read (h); printf ("%d\n", LCA (G,H)); } return 0;}
"Template" Multiplier LCA