#include<iostream> #include<algorithm> #define maxn 10005 using namespace std; int fa[maxn]; void init(){ for(int i=0;i<maxn;i++){ fa[i]=i; } } int get_ancestor(int x){ if(fa[x]==x){ return x; } return fa[x]=get_ancestor(fa[x]); } void get_union(int x,int y){ int fx=get_ancestor(x); int fy=get_ancestor(y); if(fx!=fy){ fa[fx]=fy; } } struct EdgeNode{ int from,to,weight; }; EdgeNode edge[maxn]; bool cmp(EdgeNode a,EdgeNode b){ return a.weight<b.weight; } int main(){ cout<<"请输入顶点数、边数:"; int n,e; cin>>n>>e; cout<<"请输入各条边及权重:"<<endl; for(int i=0;i<e;i++){ cin>>edge[i].from>>edge[i].to>>edge[i].weight; } sort(edge,edge+e,cmp);//按权重从小到大排序 init();//并查集初始化 int sum=0,k=0;//sum为代价,k为并入的边数 for(int i=0;i<e;i++){ if(k==n-1) break; if(get_ancestor(edge[i].from)!=get_ancestor(edge[i].to)){ get_union(edge[i].from,edge[i].to); sum=sum+edge[i].weight; k++; } } cout<<"最小代价为:"<<sum<<endl; return 0; } //请输入顶点数、边数:4 5 //请输入各条边及权重: //0 1 4 //1 2 5 //2 0 6 //2 3 7 //3 0 8 //最小代价为:16
原文:https://www.cnblogs.com/zzyf/p/13392517.html