3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
//考查知识点:克鲁斯卡尔算法 #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct node{ int sta,end,wei; }s[110]; int n,m; int father[110]; int cmp(node x,node y) { return x.wei<y.wei; } int find(int x) { int r=x; while(r!=father[r]) r=father[r]; int j=x; while(j!=r) { int k=father[j]; father[j]=r; j=k; } return r; } //int find(int x) //{ // return x==father[x]?x:find(father[x]); //} void kruskal() { int i,j; int count=1; int sum=0; for(i=1;i<=n;++i) { int fa=find(s[i].sta); int fb=find(s[i].end); if(fa!=fb) { father[fa]=fb; sum+=s[i].wei; count++; } } if(count==m) printf("%d\n",sum); else printf("?\n"); } int main() { int i,j; while(~scanf("%d%d",&n,&m),n) { for(i=1;i<=m;++i) father[i]=i; for(i=1;i<=n;++i) { scanf("%d%d%d",&s[i].sta,&s[i].end,&s[i].wei); } sort(s+1,s+n+1,cmp); kruskal(); } return 0; }
原文地址:http://blog.csdn.net/ice_alone/article/details/44700793