bzoj1602[usaco2008 OCT] Ranch Walk
Test instructions
N-point tree (with Benquan), Q asks to find the shortest distance between two points. n,q≤1000.
Exercises
Multiply to seek LCA.
Code:
1#include <cstdio>2#include <cstring>3#include <algorithm>4 #defineInc (I,J,K) for (int i=j;i<=k;i++)5 #defineMAXN 10106 using namespacestd;7 8InlineintRead () {9 CharCh=getchar ();intf=1, x=0;Ten while(ch<'0'|| Ch>'9'){if(ch=='-') f=-1; Ch=GetChar ();} One while(ch>='0'&&ch<='9') x=x*Ten+ch-'0', ch=GetChar (); A returnf*x; - } - intf[ the][maxn],h[ the][MAXN],N,Q,K,DEP[MAXN]; the structe{intT,w,n;} es[maxn*2];intESS,G[MAXN]; - voidPeintFintTintW) {es[++ess]= (e) {t,w,g[f]}; g[f]=ess; es[++ess]= (e) {f,w,g[t]}; g[t]=ess;} - voidDfsintXintFA) { - for(intI=G[X];I;I=ES[I].N)if(es[i].t!=FA) { +f[0][es[i].t]=x; h[0][ES[I].T]=ES[I].W; dep[es[i].t]=dep[x]+1; Dfs (es[i].t,x); - } + } A voidinit () { at for(k=0;(1<<k) <=n;k++); k--; -Inc (I,1, K) Inc (J,1, N) f[i][j]=f[i-1][f[i-1][j]],h[i][j]=h[i-1][j]+h[i-1][f[i-1][j]]; - } - intQueryintXinty) { - if(Dep[x]<dep[y]) swap (x, y);intt=dep[x]-dep[y],q=0; -Inc (I,0Kif(t& (1<<i)) q+=h[i][x],x=F[i][x]; in for(inti=k;i>=0; i--)if(F[i][x]!=f[i][y]) q+= (H[i][x]+h[i][y]), x=f[i][x],y=F[i][y]; - if(x==y)returnQElse returnq+= (h[0][x]+h[0][y]); to } + intMain () { -N=read (); Q=read (); Inc (I,1, N-1){intA=read (), B=read (), C=read (); PE (A,B,C);} Dfs1,0); Init (); theInc (I,1, q) {intA=read (), B=read (); printf"%d\n", query (A, b));}return 0; *}
20160913
bzoj1602[usaco2008 OCT] Ranch Walk *