http://poj.org/problem?id=1287
#include<cstdio> #include<cstdlib> #include<iostream> #define N 60 using namespace std; struct node { int x,y; int len; } city[2600]; typedef struct node NODE; int n,m,pre[N]; int cmp(const void *a,const void *b) { return ((NODE*)a)->len - ((NODE*)b)->len; } int find( int x ) { while( x!= pre[x] ) x = pre[x]; return x; } void kruskal() { int i,a,b,sum = 0; qsort(city,m,sizeof(NODE),cmp); for(i=1; i<=n; i++) pre[i] = i; for(i=0; i<m; i++) { a = find(city[i].x); b = find(city[i].y); if( a!= b) { sum += city[i].len; pre[b] = a; } } cout << sum << endl; } int main() { //freopen("3.txt","r",stdin); while( cin>>n && n ) { cin>>m; for(int i=0; i<m; i++) cin >> city[i].x >> city[i].y >> city[i].len; kruskal(); } return 0; }