Click to open link
Test instructions: Just ask the distance between two nodes
Idea: Another cut a template water problem, do not explain, do not understand the meaning of the variable can see I write this article, explain the comparative details Zoj 3195
#include <vector> #include <stdio.h> #include <string.h> #include <stdlib.h> #include < Iostream> #include <algorithm>using namespace std;typedef long long ll;const int Inf=0x3f3f3f3f;const int maxn= 40010;struct edge{int to,cost; Edge (int a,int b) {to=a;cost=b;}}; Vector<edge>g[maxn];int Dp[maxn*2][20],l[maxn*2],e[maxn*2],dis[maxn],h[maxn];bool vis[maxn];int n,k;void Dfs (int t,int deep) {k++; e[k]=t; L[k]=deep; H[t]=k; for (unsigned int i=0;i<g[t].size (); i++) {Edge e=g[t][i]; if (!vis[e.to]) {dis[e.to]=dis[t]+e.cost; Vis[e.to]=1; DFS (E.TO,DEEP+1); k++; e[k]=t; L[k]=deep; }}}void Rmq_init () {for (int i=1;i<=2*n-1;i++) dp[i][0]=i; for (int i=1, (1<<i) <=2*n-1;i++) {for (int j=1;j+ (1<<i) -1<=2*n-1;j++) {if (L[DP[J][I-1]]&L T l[dp[j+ (1<< (i-1))][i-1]]) dp[j][i]=dp[j][i-1]; Else dp[j][i]=dp[j+ (1<< (i-1))][i-1]; }}}int RMQ (int le,int ri) {Le=h[le];ri=h[ri]; if (Le>ri) swap (LE,RI); int kk=0; while ((1<< (kk+1)) <=ri-le+1) kk++; if (l[dp[le][kk]]<l[dp[ri-(1<<KK) +1][KK]]) return E[DP[LE][KK]]; else return e[dp[ri-(1<<KK) +1][KK];} int main () {int t,m,a,b,c; scanf ("%d", &t); while (t--) {scanf ("%d%d", &n,&m); memset (dis,0,sizeof (dis)); memset (vis,0,sizeof (VIS)); for (int i=0;i<maxn;i++) g[i].clear (); for (int i=0;i<n-1;i++) {scanf ("%d%d%d", &a,&b,&c); G[a].push_back (Edge (b,c)); G[b].push_back (Edge (a,c)); } k=0;vis[1]=1; DFS (a); Rmq_init (); while (m--) {scanf ("%d%d", &a,&b); int Ans=dis[a]+dis[b]-2*dis[rmq (A, b)]; printf ("%d\n", ans); }} return 0;}
HDU 2586 LCA Transfer RMQ