Kruskal算法
#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; }
相关推荐
湾区人工智能 2020-11-20
Pokemogo 2020-11-16
baijingjing 2020-11-16
baijingjing 2020-11-15
Site 2020-11-07
lwnylslwnyls 2020-11-06
justaipanda 2020-11-05
MachineIntellect 2020-11-02
xueyuediana 2020-10-30
GeraldJones 2020-10-30
Tips 2020-10-29
baijingjing 2020-10-28
baijingjing 2020-10-27
硕鼠 2020-10-26
playoffs 2020-10-26
scuyxi 2020-10-25
playoffs 2020-10-25
yise001 2020-10-23