标签:c++ from pre efi swap oid for sort clu
#include <bits/stdc++.h>
#define MAXN 200005
using namespace std;
int node,edge,ans=0,k=0;
int fat[MAXN],siz[MAXN];
struct EDGE
{
int from,to,cost;
} e[MAXN];
bool cmp(EDGE a,EDGE b) {return a.cost<b.cost;}
int Find(int x){ return (fat[x]==x)? x : fat[x]=Find(fat[x]); } //查
void unionn(int x,int y)//并
{
x=Find(x); y=Find(y);
if(siz[x]>siz[y]) swap(x,y);
fat[x]=y; siz[y]+=siz[x];
}
bool kruskal()
{
sort(e+1,e+edge+1,cmp);
//贪心,排序
for(int i=1;i<=edge;++i)
{
if(k==node-1) break;
if(Find(e[i].from) != Find(e[i].to))
{
unionn(e[i].from,e[i].to);
ans+=e[i].cost; ++k;
}
}
return (k==node-1);
}
int main()
{
scanf("%d%d",&node,&edge);
//node点数,edge边数
for(int i=1;i<=edge;++i) scanf("%d%d%d",&e[i].from,&e[i].to,&e[i].cost);
//邻接矩阵
for(int i=1;i<=node;++i) {fat[i]=i;siz[i]=1;}
//初始化
if(kruskal()) printf("%d",ans);
return 0;
}
标签:c++ from pre efi swap oid for sort clu
原文地址:https://www.cnblogs.com/cyl-oi-miracle/p/13401477.html