Recent public ancestors,
Multiply on the tree, LCA,
FA [i] [j] represents the ancestor of the I node up to 2j
Much like DP,
K belongs to [1, log (n)], F [x] [k] = f [f [x] [k-1]] [k-1]
When calculating the LCA,
Set d [x] >= d [y] First
Binary split
Try to go up from x k = 2log (n), ~~,21,20,
Check to see if the point is darker than Y
For each check, if, x= f [x] [K]
If not, then f [x] [k]! = f [y] [K]
make x = f [x] [k], y = f [y] [K]
Finally, if x = y, LCA (x, y) =y
Look at the code
#include <cstdio>#include<iostream>#include<string>#include<bits/stdc++.h>using namespacestd;#defineMAXN 50010intfa[maxn][ -];//F[i][j] Represents the ancestor of the 2^j of IintDEP[MAXN];//DepthintDIS[MAXN];//Distance to root nodestructedge{intv; intW; intNXT;} E[MAXN*2];intHEAD[MAXN];intt,n,m,cnt;intT//Exponential Power t= (log (n)/log (2)) +1voidAddintXintYintz) {e[++cnt].v=y; E[CNT].W=Z; E[CNT].NXT=Head[x]; HEAD[X]=CNT;} Queue<int>Q;voidBFs () {//pretreatmentQ.push (1); dep[1]=1; while(Q.size ()) {intx=Q.front (); Q.pop (); for(intI=head[x];i;i=e[i].nxt) { inty=e[i].v; if(Dep[y])Continue; Dep[y]=dep[x]+1; Dis[y]=dis[x]+E[I].W; fa[y][0]=x; for(intj=1; j<=t;j++) {Fa[y][j]=fa[fa[y][j-1]][j-1]; } q.push (y); } } }intLcaintXinty) {if(dep[x]>Dep[y]) swap (x, y); for(inti=t;i>=0; i--) { if(dep[fa[y][i]]>=Dep[x]) {y=Fa[y][i]; } } if(x==y)returnx; for(inti=t;i>=0; i--) { if(fa[x][i]!=Fa[y][i]) {x=Fa[x][i]; Y=Fa[y][i]; } } returnfa[x][0];}intMain () {T=(int) (log (n)/log (2))+1; memset (Head,0,sizeof(head)); memset (DEP,0,sizeof(DEP)); CNT=0; CIN>>n>>m; for(intI=1, x,y,z;i<n;i++) {cin>>x>>y>>Z; Add (x, y, z); Add (y,x,z); } BFS (); for(intI=1, x,y,len;i<=m;i++) { //AskCin>>x>>y; cout<<lca (x, y) <<Endl; Len=dis[x]+dis[y]-2*Dis[lca (x, y)]; cout<<len<<Endl; } return 0;}/*2 3, 4, 5, 6, 7 8, 9, 510 7*/
Okay, OK.
Tree, LCA, recent public ancestor, multiplication