【bzoj 1602】[Usaco2008 Oct]牧场行走

来源:互联网 发布:淘宝怎么解除微博绑定 编辑:程序博客网 时间:2024/06/05 01:06

 [Usaco2008 Oct]牧场行走

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 1906  Solved: 998
[Submit][Status][Discuss]

Description

N头牛(2<=n<=1000)别人被标记为1到n,在同样被标记1到n的n块土地上吃草,第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走,第i条边连接第Ai,Bi块牧场,第i条边的长度是Li(1<=Li<=10000)。 这些边被安排成任意两头奶牛都可以通过这些边到达的情况,所以说这是一棵树。 这些奶牛是非常喜欢交际的,经常会去互相访问,他们想让你去帮助他们计算Q(1<=q<=1000)对奶牛之间的距离。

Input

*第一行:两个被空格隔开的整数:N和Q

 *第二行到第n行:第i+1行有两个被空格隔开的整数:AI,BI,LI

*第n+1行到n+Q行:每一行有两个空格隔开的整数:P1,P2,表示两头奶牛的编号。

Output

*第1行到第Q行:每行输出一个数,表示那两头奶牛之间的距离。

Sample Input

4 2
2 1 2
4 3 2
1 4 3
1 2
3 2

Sample Output

2
7
我为什么至今不会倍增lca。只会树链剖分的……

#include<cstdio>using namespace std;#define maxn 1050int n,m;int len,h[maxn],nx[maxn<<1],to[maxn<<1],co[maxn<<1];int fa[maxn],dep[maxn],top[maxn],sum[maxn],ch[maxn],size[maxn];void add_edge(int a,int b,int c){    to[++len]=b;nx[len]=h[a];h[a]=len;co[len]=c;    to[++len]=a;nx[len]=h[b];h[b]=len;co[len]=c;} void dfs1(int nd,int pr){    fa[nd]=pr;size[nd]=1;dep[nd]=dep[pr]+1;    for(int i=h[nd];i;i=nx[i]){        if(to[i]==fa[nd]) continue;        sum[to[i]]=sum[nd]+co[i];//      printf("%d %d\n",nd,to[i]);        dfs1(to[i],nd);        size[nd]+=size[to[i]];        if(size[to[i]] > size[ch[nd]]){            ch[nd]=to[i];        }    }}void dfs2(int nd,int tp){    top[nd]=tp;    if(ch[nd]!=0)dfs2(ch[nd],tp);    for(int i=h[nd];i;i=nx[i]){        if(to[i]==fa[nd] || to[i]==ch[nd]) continue;        dfs2(to[i],to[i]);    }}int lca(int na,int nb){    while(top[na]!=top[nb]){        dep[top[na]] > dep[top[nb]] ? na=fa[top[na]] : nb=fa[top[nb]];    }    return dep[na]<dep[nb]?na:nb;}int main(){    scanf("%d%d",&n,&m);    for(int i=0;i<n-1;i++){        int a,b,c;scanf("%d%d%d",&a,&b,&c);add_edge(a,b,c);    }    dfs1(1,0);dfs2(1,1);    for(int i=0;i<m;i++){        int a,b;        scanf("%d%d",&a,&b);        int t=lca(a,b);        printf("%d\n",sum[a]-sum[t]+sum[b]-sum[t]);    }    return 0;}



0 0