POJ 2377 Bad Cowtractors

最大生成树。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;

const int maxn=1500;
int n,m;
struct X
{
    int u,v;
    long long val;
} e[maxn*maxn];
int f[maxn];

int Find(int x)
{
    if(x!=f[x]) return f[x]=Find(f[x]);
    return f[x];
}

bool cmp(const X&a,const X&b)
{
    return a.val>b.val;
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1; i<=n; i++) f[i]=i;
        for(int i=0; i<m; i++)
            scanf("%d%d%lld",&e[i].u,&e[i].v,&e[i].val);
            
        int d=n;
        sort(e,e+m,cmp);
        long long ans=0;
        for(int i=0; i<m; i++)
        {
            int fx=Find(e[i].u);
            int fy=Find(e[i].v);
            if(fx!=fy)
            {
                f[fx]=fy;
                ans=ans+e[i].val;
                d--;
            }
        }
        if(d!=1) ans=-1;
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5362178.html