Portal: A and B and lecture Rooms
Test instructions: Given a tree, the number of points that are equal to the point u,v each query is reached.
Analysis: Consider the situation as follows:
1.abs (Deep[u]-deep[v])%2==1, there must be no point at which the u,v distance is equal.
2. If DEEP[U]==DEEP[V], Ans=n-num[lca (u,v) u in the Son tree]-num[lca (u,v) v in the Son Tree].
3. If DEEP[U]!=DEEP[V], in the path from U to V to find u,v equal to the node x, then ans=num[x]-num[u in the X son tree].
#include <algorithm>#include<iostream>#include<cstring>#include<cstdlib>#include<cstdio>#include<queue>#include<map>#defineN 200010#defineLL Long Long#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1using namespacestd;structedge{intV,next; Edge () {} Edge (intVintnext): V (v), next (next) {}} E[n];intHead[n],tot;intNum[n],deep[n];intfa[n][ -];voidinit () {memset (head,-1,sizeof(head)); Tot=0;}voidAddedge (intUintv) {E[tot]=Edge (V,head[u]); Head[u]=tot++;}voidDfsintXintf) { for(intI=1; i< -; i++) { if(deep[x]< (1<<i)) Break; Fa[x][i]=fa[fa[x][i-1]][i-1]; } for(intI=HEAD[X]; ~i; I=E[i].next) { intv=e[i].v; if(v==f)Continue; fa[v][0]=x; DEEP[V]=deep[x]+1; DFS (V,X); NUM[X]+=Num[v]; }}intLcaintXinty) { if(deep[x]<Deep[y]) swap (x, y); intt=deep[x]-Deep[y]; for(intI=0; i<= +; i++) if((1<<i) &t) x=Fa[x][i]; for(intI= +; i>=0; i--) { if(fa[x][i]!=Fa[y][i]) {x=Fa[x][i]; Y=Fa[y][i]; } } if(x==y)returnx; returnfa[x][0];}intMain () {intn,m; while(SCANF ("%d", &n) >0) {init (); for(intI=1; i<n; i++) { intu,v; scanf ("%d%d",&u,&v); Addedge (U,V); Addedge (V,u); } for(intI=1; i<=n;i++) num[i]=1; deep[1]=1; DFS (1,0); scanf ("%d",&m); while(m--) { intx, y; scanf ("%d%d", &x,&y); if(deep[x]<Deep[y]) swap (x, y); if((Deep[x]-deep[y]) &1) printf ("0\n"); Else { intXy=lca (x, y), tx=x; intT= (deep[x]+deep[y]-2*DEEP[XY])/2-1; for(intI=0;i< -; i++)if(t& (1<<i)) x=Fa[x][i]; if(deep[tx]==Deep[y]) {T=deep[y]-deep[xy]-1; for(intI=0;i< -; i++)if(t& (1<<i)) y=Fa[y][i]; printf ("%d\n", n-num[x]-Num[y]); } Elseprintf"%d\n", num[fa[x][0]]-num[x]); } } }}
View Code
CF 519E (multiplication of the tree to seek LCA)