您的位置:首页 > 产品设计 > UI/UE

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

2016-02-26 14:07 423 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: