bzoj1602[Usaco2008 Oct]牧场行走*

bzoj1602[Usaco2008 Oct]牧场行走

题意:

n点树(有边权),q个询问求两个点之间的最短距离。n,q≤1000。

题解:

倍增求lca。

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define inc(i,j,k) for(int i=j;i<=k;i++)
 5 #define maxn 1010
 6 using namespace std;
 7 
 8 inline int read(){
 9     char ch=getchar(); int f=1,x=0;
10     while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
11     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
12     return f*x;
13 }
14 int f[15][maxn],h[15][maxn],n,q,k,dep[maxn];
15 struct e{int t,w,n;}es[maxn*2]; int ess,g[maxn];
16 void pe(int f,int t,int w){es[++ess]=(e){t,w,g[f]}; g[f]=ess; es[++ess]=(e){f,w,g[t]}; g[t]=ess;}
17 void dfs(int x,int fa){
18     for(int i=g[x];i;i=es[i].n)if(es[i].t!=fa){
19         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);
20     }
21 }
22 void init(){
23     for(k=0;(1<<k)<=n;k++); k--;
24     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]];
25 }
26 int query(int x,int y){
27     if(dep[x]<dep[y])swap(x,y); int t=dep[x]-dep[y],q=0;
28     inc(i,0,k)if(t&(1<<i))q+=h[i][x],x=f[i][x];
29     for(int i=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];
30     if(x==y)return q;else return q+=(h[0][x]+h[0][y]);
31 }
32 int main(){
33     n=read(); q=read(); inc(i,1,n-1){int a=read(),b=read(),c=read(); pe(a,b,c);} dfs(1,0); init();
34     inc(i,1,q){int a=read(),b=read(); printf("%d\n",query(a,b));} return 0;
35 }

 

20160913

posted @ 2016-09-16 15:56  YuanZiming  阅读(172)  评论(0编辑  收藏  举报