contesthunter 6201 走廊泼水节【克鲁斯卡尔+并查集】

很有意思的题,所以还是截lyddalao的课件

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=6005;
int T,n,f[N],s[N];
long long ans;
struct qwe
{
    int u,v,w;
}a[N];
bool cmp(const qwe &a,const qwe &b)
{
    return a.w<b.w;
}
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int zhao(int x)
{
    return x==f[x]?x:zhao(f[x]);
}
int main()
{
    T=read();
    while(T--)
    {
        n=read();ans=0;
        for(int i=1;i<n;i++)
            a[i].u=read(),a[i].v=read(),a[i].w=read();
        sort(a+1,a+n,cmp);
        for(int i=1;i<=n;i++)
            f[i]=i,s[i]=1;
        for(int i=1;i<n;i++)
        {
            int fu=zhao(a[i].u),fv=zhao(a[i].v);
            ans+=1ll*s[fu]*s[fv]*(a[i].w+1)-a[i].w-1;//cerr<<ans<<endl;
            f[fu]=fv;
            s[fv]+=s[fu];
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/9330518.html