uva1664(贪心+并查集)

sum[x]+num[y]*z>sum[y]+num[x]*z贪心更新父节点

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace std;
const int maxn=200000+100;
typedef long long ll;
int c[maxn];
struct note
{
    int u,v,w;
    bool operator <(const note &p) const
    {
        return w>p.w;
    }
}aa[maxn];
int num[maxn];
ll sum[maxn];
int f[maxn];
int n;
int found(int x)
{
    if(x==c[x]) return x;
    else return c[x]=found(c[x]);
}
void unit(int x,int y,int z)
{
    x=found(x);
    y=found(y);
    if(sum[x]+(ll)num[y]*(ll)z>sum[y]+(ll)num[x]*(ll)z)//更新父节点
    {

         c[y]=x;
         num[x]+=num[y];
         sum[x]+=(ll)num[y]*(ll)z;

    }
    else
    {

         c[x]=y;
         num[y]+=num[x];
         sum[y]+=(ll)num[x]*(ll)z;

    }
}
void init(int nn)
{
    for(int i=1;i<=nn;i++)
    {
        num[i]=1;
        sum[i]=0LL;
        c[i]=i;
    }
}
int main()
{
    while(~scanf("%d",&n))
    {
        init(n);
       for(int i=1;i<n;i++)
         scanf("%d%d%d",&aa[i].u,&aa[i].v,&aa[i].w);
         sort(aa+1,aa+n);
         for(int i=1;i<n;i++)
         {
              unit(aa[i].u,aa[i].v,aa[i].w);
         }
         printf("%lld\n",sum[found(1)]);
    }
    return 0;
}

 

posted on 2018-01-30 17:21  发牌员  阅读(137)  评论(0编辑  收藏  举报

导航