UVA 1664(p382)----Conquer a New Region

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=200000+50;
struct point
{
    LL u,v,w;
};
point g[maxn];
LL sum[maxn],n;
LL fa[maxn],num[maxn];
LL Find(LL x)
{
    return x==fa[x]?x:fa[x]=Find(fa[x]);
}
void Union(LL x,LL y)
{
    fa[x]=y;
}
int cmp(point a,point b)
{
    return a.w>b.w;
}
void solve()
{
    for(int i=0; i<n-1; i++)
    {
        LL x=Find(g[i].u);
        LL y=Find(g[i].v);
        LL tmp1=sum[x]+num[y]*g[i].w;
        LL tmp2=sum[y]+num[x]*g[i].w;
        if(tmp1>tmp2) {swap(x,y);swap(tmp1,tmp2);}
        Union(x,y);
        sum[y]=tmp2;
        num[y]+=num[x];
    }
    printf("%lld\n",sum[Find(n)]);
}
void init()
{
    memset(sum,0,sizeof(sum));
    for(int i=1; i<=n; i++) fa[i]=i;
    for(int i=1; i<=n; i++) num[i]=1;
}
int main()
{
    while(scanf("%lld",&n)==1)
    {
        init();
        for(int i=0; i<n-1; i++)
            scanf("%lld%lld%lld",&g[i].u,&g[i].v,&g[i].w);
        sort(g,g+n-1,cmp);
        solve();
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值