BZOJ2435: [Noi2011]道路修建

【传送门:BZOJ2435


简要题意:

  给出n个点,n-1条边,显然是一棵树,每条边有权值,而建设每条边的代价是这条边的权值乘上这条边左边的点数减去右边的点数的绝对值

  求出总代价


题解:

  很水

  我们默认点1为树的根,DFS将每个点遍历一遍,求出每个点的深度和子树点数

  然后遍历一遍所有的边,ans+=边权*abs(n-深度更深的点的子树点数*2)

  为什么是n-深度更深的点的子树点数*2,很简单,这条边右边的点数=深度更深的点的子树点数,那自然右边的点数就等于剩下的点数咯,就=n-深度更深的点的子树点数


参考代码:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
struct node
{
    int x,y,d,next;
}a[2100000];int len,last[1100000];
int tot[1100000],dep[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;
}
void dfs(int x,int fa)
{
    tot[x]=1;dep[x]=dep[fa]+1;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(y!=fa)
        {
            dfs(y,x);
            tot[x]+=tot[y];
        }
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<n;i++)
    {
        int x,y,d;
        scanf("%d%d%d",&x,&y,&d);
        ins(x,y,d);ins(y,x,d);
    }
    dfs(1,0);
    LL ans=0;
    for(int i=1;i<=len;i+=2)
    {
        int x=a[i].x,y=a[i].y;
        if(dep[x]>dep[y]) swap(x,y);
        ans+=LL(a[i].d)*abs(n-tot[y]-tot[y]);
    }
    printf("%lld
",ans);
    return 0;
}

 

原文地址:https://www.cnblogs.com/Never-mind/p/8455268.html