main.cpp
#include<iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N=50005;
int head[N],tot=0,n,m,cnt=0,fa[N];
int ans=0;
struct Edge{
int u,v;//边的两个顶点
int w;//边的权值
inline friend bool operator <(Edge a,Edge b){
return a.w<b.w;}
};
Edge edges[N];
inline int find(int x){
if(fa[x]==x)
return x;
else {
fa[x]=find(fa[x]);
return fa[x];
}
}
int main(){
freopen("input.in","r",stdin);
freopen("output.out","w",stdout);
cin>>n; //n为结点个数
cin>>m; //m为边的个数
for(int i=1;i<=n;i++)fa[i]=i; //起初每个顶点都独自在一个集合
for(int i=1;i<=m;i++){//读入m条边的起始点和权值
cin>>edges[i].u;
cin>>edges[i].v;
cin>>edges[i].w;
}
sort(edges+1,edges+m+1); //按照边的权值从小到大排序
cout<<"排序之后的结果(顶点u,顶点v,权值):"<<endl;
for(int i=1;i<=m;i++)
cout<<"("<<edges[i].u<<","<<edges[i].v<<","<<edges[i].w<<")"<<endl;
// cout<<"构成最小生成树的边为(顶点u,顶点v,权值):"<<endl;
for(int i=1;i<=m;i++){
if(cnt==n-1)break;
int u,v,x,y;
u=edges[i].u;//获得边的一个顶点u
v=edges[i].v;//获得边的另一个顶点v
x=find(u);//查找顶点u所在的集合
y=find(v);//查找顶点v所在的集合
cout<<"目前在处理的边为:(顶点u,顶点v,权值)";
cout<<"("<<edges[i].u<<","<<edges[i].v<<","<<edges[i].w<<")"<<endl;
cout<<"两个顶点所在的集合分别为:"<<fa[edges[i].u]<<","<<fa[edges[i].v]<<endl;
if(x==y){
cout<<"边的两个顶点在同一集合,故被舍弃"<<endl;
cout<<endl<<endl;
continue;
}
else{//只有当两个顶点不在同一个集合时才输出并且合并
cout<<"边("<<edges[i].u<<","<<edges[i].v<<","<<edges[i].w<<")被加入到最小生成树中"<<endl;
fa[x]=y;
cout<<"顶点"<<edges[i].u<<"被加入到集合"<<fa[edges[i].u]<<"中"<<endl;
cnt++;
ans+=edges[i].w;
}
cout<<endl<<endl;
}
cout<<"最小代价为:"<<ans<<endl;
fclose(stdin);
fclose(stdout);
}