Reference Blog
Think carefully: The recent public ancestor, in fact, the search time back, connect these two points, that the lowest depth is certainly the nearest public ancestor Ah.
Then it can become a RMQ problem.
#include <stdio.h>#include<iostream>#include<algorithm>#include<string.h>using namespacestd;Const intmax_=41005;intIp,tot;structtree{//Tree intto ; intNext; intv;};structTree a[max_*2];intFIRST[MAX_];//the first occurrence of the positionintEDGE[MAX_];//side Record NextintDe[max_*2];//DepthintId[max_*2];//Traverse number (includes back)intDIS[MAX_];//the distance to the root. intDp[max_*2][ -];//St table, which records the subscriptBOOLVIS[MAX_];//Tag ArrayvoidAdd_edge (intXintYintV//Achievements{a[++ip].to=y; A[IP].V=v; A[ip].next=Edge[x]; EDGE[X]=IP;}voidDfsintXintDeep//DFS Traversal{ if(vis[x]==0) {First[x]=tot;//record the first timevis[x]=1; } De[tot]=deep,id[tot++]=x; for(intI=edge[x];i;i=A[i].next) { intgo_to=a[i].to; if(vis[go_to])Continue; intgo_v=a[i].v; DIS[GO_TO]=dis[x]+go_v;//with the new distanceDFS (go_to,deep+1); Id[tot]=x,de[tot++]=Deep ; }}intMin (intXintY//finding the minimum depth{ if(de[x]>De[y])returny; Else returnx;}voidRmq_st (intLen) { for(intI=0; i<len;i++)//Initializedp[i][0]=i; for(intj=1;(1<<J) <=len;j++) for(intI=0; i+ (1<<J)-1<len;i++) {Dp[i][j]=min (dp[i][j-1],dp[i+ (1<< (J-1))][j-1]); }}intRmq_question (intLintR) { intk=0; while((1<< (k +1)) <=r-l+1) k++; returnMin (dp[l][k],dp[r-(1<<K) +1][k]);}voidItin () {memset (Vis,0,sizeof(VIS)); memset (DIS,0,sizeof(DIS)); Memset (Edge,0,sizeof(Edge)); Tot=0; IP=0;}intMain () {intT; CIN>>T; while(t--) {itin (); intn,m; CIN>>n>>m; for(intI=0; i<n-1; i++) { intx,y,v; CIN>>x>>y>>v; Add_edge (X,Y,V); Add_edge (Y,X,V); } DFS (1,0); Rmq_st (TOT); for(intI=0; i<m;i++) { intu,v,k; CIN>>u>>v; if(First[u]>first[v])//The first appearance is left{k=rmq_question (First[v],first[u]); } Elsek=rmq_question (First[u],first[v]); inttemp=dis[u]+dis[v]-(2*Dis[id[k]]); cout<<temp<<Endl; }} return 0;}
The RMQ method of LCA