< topic links >
Main topic:
Give a tree and ask the number of the nearest public ancestor of any two points.
Problem Solving Analysis:
LCA template problem, the following is the online multiplication algorithm solution.
1#include <cstdio>2#include <cstring>3#include <algorithm>4#include <cmath>5 using namespacestd;6 7 Const intN = 1e4+Ten;8 Const intINF =0x3f3f3f3f;9 structedge{Ten intTo,next; One}edge[n<<1]; A intCnt,head[n]; - intdep[n],f[n][ *]; - intNinch[N]; the voidAddedge (intUintv) { -edge[++cnt].to=v,edge[cnt].next=Head[u]; -head[u]=CNT; - } + voidDfsintUintFA) {//mark the depth of all nodes - for(intI=head[u];~i;i=Edge[i].next) { + intv=edge[i].to; A if(V==FA)Continue; at if(!Dep[v]) { -dep[v]=dep[u]+1; -f[v][0]=u; - DFS (v,u); - } - } in } - voidInit () {//preprocessing multiplication Arrays to for(intj=1;(1<<J) <=n;j++) + for(intI=1; i<=n;i++) -f[i][j]=f[f[i][j-1]][j-1]; the } * intLCA (intXinty) { $ if(dep[x]<Dep[y]) swap (x, y);Panax Notoginseng intd=dep[x]-Dep[y]; - for(intI=0;(d >>i)! =0; i++) the if((d>>i) &1) x=F[x][i]; + if(x==y)returnx; A for(intI= -; i>=0; i--) the if(f[x][i]!=F[y][i]) { +x=F[x][i]; -y=F[y][i]; $ } $ returnf[x][0]; - } - intMain () { the intT;SCANF ("%d",&T); - while(t--){Wuyiscanf"%d",&n); theCnt=0; - intu,v; Wumemset (head,-1,sizeof(head)); - for(intI=1; i<n;i++){ Aboutscanf"%d%d",&u,&v); $ Addedge (u,v); - inch[v]++; - } -memset (DEP,0,sizeof(DEP)); A intRoot; + for(intI=1; i<=n;i++) the if(!inch[i]) root=i;//find the root of the tree -dep[root]=1; $DFS (root,-1); the init (); thescanf"%d%d",&u,&v); theprintf"%d\n", LCA (u,v)); the } - return 0; in}
2018-10-18
POJ 1330 Nearest Common Ancestors (template title) (LCA) "multiplier"