其中n和m分别表示图的顶点数和边数。
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<string> #include<cmath> #include<map> #include<algorithm> using namespace std; const int maxn=11; const int maxm=20; int n,m; struct Edge { int u,v,w; } edges[maxm]; class set { public: void makeset(int n) { for(int i=0; i<n; i++) { father[i]=i; rank[i]=1; } } int findset(int x) { if(x!=father[x]) father[x]=findset(father[x]); return father[x]; } void unionset(int x,int y) { x=findset(x); y=findset(y); if(x==y) return; if(rank[x]>rank[y]) { father[y]=x; rank[x]+=rank[y]; } else { father[x]=y; rank[y]+=rank[x]; } } private: int father[maxn]; int rank[maxn]; } ufs; int cmp(const void* a,const void* b) { Edge aa=*(const Edge*)a, bb=*(const Edge*)b; return aa.w-bb.w; } void kruskal() { int sumw=0,num=0; int u,v; ufs.makeset(n); for(int i=0; i<m; i++) { u=edges[i].u; v=edges[i].v; if(ufs.findset(u)!=ufs.findset(v)) { printf("%d %d %d\n",u,v,edges[i].w); ufs.unionset(u,v); sumw+=edges[i].w; num++; } if(num>=n-1) break; } printf("weight of MST is %d\n",sumw); } int main() { while(~scanf("%d%d",&n,&m)) { for(int i=0; i<m; i++) scanf("%d%d%d",&edges[i].u,&edges[i].v,&edges[i].w); qsort(edges,m,sizeof(edges[0]),cmp); kruskal(); } return 0; }