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\n",ans);
    return 0;
}

 

转载于:https://www.cnblogs.com/Never-mind/p/8455268.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值