kruskal——宿命的PSS

https://vijos.org/p/1579
题解在这里
http://blog.csdn.net/fop_zz/article/details/70670069
但是代码我的好

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define Ll long long
using namespace std;
struct cs{Ll x,y,v;}a[20005];
Ll fa[20005],size[20005];
Ll X,Y,n,ans;
bool cmp(cs a,cs b){return a.v<b.v;}
int get(int x){
    if(!fa[x])return x;
    return fa[x]=get(fa[x]);
}
int main()
{
    scanf("%lld",&n);
    for(int i=1;i<n;i++)scanf("%lld%lld%lld",&a[i].x,&a[i].y,&a[i].v);
    sort(a+1,a+n,cmp);
    for(int i=1;i<=n;i++)size[i]=1;
    for(int i=1;i<n;i++){
        X=get(a[i].x); Y=get(a[i].y);
        ans+=(size[X]*size[Y]-1)*(a[i].v+1)+a[i].v;
        fa[X]=Y; size[Y]+=size[X];
    }
    printf("%lld",ans);
}
posted @ 2017-04-25 09:37  largecube233  阅读(150)  评论(0编辑  收藏  举报