最小生成树-克鲁斯卡尔模板

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int fat[5001];
int tot;
struct node{
    int x,y,z;//结构体保存起点x,终点y,以及边权z
}f[200001];
int find(int x)//路径压缩
{
    if(fat[x] != x) 
        fat[x] = find(fat[x]);
    return fat[x];
}
void unionn(int x,int y)//合并
{
    int x1=find(x),y1=find(y);
    fat[y1]=x1;
}
bool cmp(node a,node b)
{
    return a.z<b.z;//快排的规则
}
int main()
{
    int m,n;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
        scanf("%d%d%d",&f[i].x,&f[i].y,&f[i].z);

    for(int i=1;i<=n;i++) fat[i]=i;//自己叫自己爸爸

    sort(f+1,f+m+1,cmp);//快排

    int k=0;//计数

    for(int i=1;i<=m;i++)
    {
        if(find(f[i].x)!=find(f[i].y))//不在同一集合内
        {

            unionn(f[i].x,f[i].y);

            tot+=f[i].z;//计算权值和

            k++;
        }
    }
    if(k<n-1) printf("orz");//判断是否连通

    else printf("%d",tot);
}

  

原文地址:https://www.cnblogs.com/Roni-i/p/8674907.html