1 #include <iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<algorithm> 5 #define MAXN 30 6 #define MAXM 1000 7 using namespace std; 8 9 struct edge 10 { 11 int u,v,w; 12 }edges[MAXM]; 13 int parent[MAXN]; 14 int N,m; 15 int i,j; 16 int sumweight; 17 void UFset() 18 { 19 for(i=1;i<=N;i++) 20 { 21 parent[i]=-1; 22 } 23 } 24 int Find(int x) 25 { 26 int s; 27 for(s=x;parent[s]>=0;s=parent[s]); 28 while(s!=x) 29 { 30 int tmp=parent[x]; 31 parent[x]=s; 32 x=tmp; 33 } 34 return s; 35 } 36 void Union (int R1,int R2) 37 { 38 int r1=Find(R1); 39 int r2=Find(R2); 40 int tmp=parent[r1]+parent[r2]; 41 if(r1<r2) 42 { 43 parent[r2]=r1; 44 parent[r1]=tmp; 45 } 46 else 47 { 48 parent[r1]=r2; 49 parent[r2]=tmp; 50 } 51 } 52 int cmp(const void *a,const void *b) 53 { 54 edge aa=*(const edge *)a; 55 edge bb=*(const edge *)b; 56 if(aa.w>bb.w) 57 return 1; 58 else return -1; 59 } 60 void Kruskal() 61 { 62 int num=0; 63 int u,v; 64 UFset(); 65 for(i=0; i<m; i++) 66 { 67 u=edges[i].u; 68 v=edges[i].v; 69 if(Find(u)!=Find(v)) 70 { 71 sumweight+=edges[i].w; 72 num++; 73 Union(u,v); 74 } 75 if(num>=N-1) 76 break; 77 } 78 } 79 int main() 80 { 81 while(1) 82 { 83 char c,cc; 84 scanf("%d",&N); 85 if(N==0)break; 86 int mi=0;//±ßµÄÐòºÅ 87 int numm; 88 for(i=0; i<N-1; i++) 89 { 90 getchar(); 91 scanf("%c",&c); 92 scanf("%d",&numm); 93 for(j=0;j<numm;j++) 94 { 95 getchar(); 96 scanf("%c %d",&cc,&edges[mi].w); 97 edges[mi].u=c-'A'+1; 98 edges[mi].v=cc-'A'+1; 99 //printf("%d %d ",edges[mi].u,edges[mi].v); 100 mi++; 101 } 102 } 103 m=mi; 104 qsort(edges,m,sizeof(edges[0]),cmp); 105 sumweight=0; 106 Kruskal(); 107 printf("%d ",sumweight); 108 } 109 return 0; 110 }