http://poj.org/problem?id=1251
#include<algorithm> #include<iostream> #include<cstdlib> #include<cstdio> #include<cmath> using namespace std; #define maxm 205 #define maxn 30 struct edge { int u,v,w; } edges[maxm]; int parent[maxn],num,sum; int N,i,j; void ufset() { for(i=0; i<maxn; i++) parent[i]=-1; } int find(int x) { int s; for(s=x; parent[s]>=0; s=parent[s]); while(s!=x) { int tmp=parent[x]; parent[x]=s; x=tmp; } return s; } void Union(int R1,int R2) { int r1=find(R1),r2=find(R2); int tmp=parent[r1]+parent[r2]; if(parent[r1]>parent[r2]) { parent[r1]=r2; parent[r2]=tmp; } else { parent[r2]=r1; parent[r1]=tmp; } } int cmp(const void* a,const void* b) { return ((edge*)a)->w-((edge*)b)->w; } int kruskal(int num) { int min = 0; int k = 0; qsort(edges,num, sizeof(edges[0]), cmp); for(int i = 0; i < num; i++) { if(find(edges[i].v)!= find(edges[i].u)) { Union(edges[i].v,edges[i].u); min+=edges[i].w; k++; } if(k == N-1) return min; } return min; } int main() { int r, k, dis; char st, en; // freopen("1.txt","r",stdin); while(1) { ufset(); k= 0; cin>>N; if(N == 0) break; for(i = 1; i < N; i++) { cin>> st >> r; for(j = 0; j < r; j++) { cin>> en >> dis; edges[k].u= (int)(st-'A'+1); edges[k].v= (int)(en-'A'+1); edges[k].w= dis; k++; } } cout<< kruskal(k) << endl; } return 0; }