最小生成树 hdu 1233 模板题

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+7;
int n,m,cot,sum;
struct edge
{
    int u,v,w;
    bool operator <(const edge &b)const{
        return w<b.w;
    }
}g[maxn];
int f[maxn];
int Find(int x)
{
    return f[x]==x?x:f[x]=Find(f[x]);
}

void kruskal()
{
    cot=0;
    sort(g,g+m);
    for(int i=0; i<m; i++){
        int t1=Find(g[i].u);
        int t2=Find(g[i].v);
        if(t1!=t2){
            f[t2]=t1;
            cot++;
            sum=sum+g[i].w;
        }
        if(cot==n-1) break;
    }
    return ;
}
int main()
{
    while(~scanf("%d",&n)&&n){
        m=n*(n-1)/2;
        sum=0;
        for(int i=0;i<=n;i++)f[i]=i;
        for(int i=0;i<m;i++){
             scanf("%d%d%d",&g[i].u,&g[i].v,&g[i].w);
        }
        kruskal();
        printf("%d
",sum);
    }
    return 0;
}
/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/
原文地址:https://www.cnblogs.com/lalalatianlalu/p/8158469.html