bzoj2435: [Noi2011]道路修建

直接DFS就可以了。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;

int n;

struct node
{
    int x,y,d,next;
}a[2100000];int len,last[1100000];
void ins(int x,int y,int d)
{
    len++;
    a[len].x=x;a[len].y=y;a[len].d=d;
    a[len].next=last[x];last[x]=len;
}

int w[1100000],tot[1100000];
void dfs(int x)
{
    tot[x]=1;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(tot[y]==-1)
        {
            w[y]=a[k].d;
            dfs(y);
            tot[x]+=tot[y];
        }
    }
}
int main()
{
    int x,y,d;
    scanf("%d",&n);
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<n;i++)
    {
        scanf("%d%d%d",&x,&y,&d);
        ins(x,y,d);ins(y,x,d);
    }
    
    memset(tot,-1,sizeof(tot));
    dfs(1);
    
    LL ans=0;
    for(int i=2;i<=n;i++)
    {
        LL t=LL(w[i])*abs( LL(tot[1]-tot[i]) - LL(tot[i]) );
        ans+=t;
    }
    printf("%lld
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/AKCqhzdy/p/7884377.html