http://ac.jobdu.com/problem.php?pid=1154
// 北大10机试
// 1154:Jungle Roads
//
// WA:原因,初始化时为1~SIZE-1,而使用时ch-'A',是从0开始的。
// 但是,本地测试却与答案相同!所以,优点隐蔽。
// 所以初始化时,为0~SIZE-1时,就安全保险了。
// 还需要养成习惯,做到点的开始为1。除非规定了第一个点为0.
#include <stdio.h>
#include <algorithm>
#define SIZE 30
#define MAXSIZE 350
using namespace std;
struct Edge
{
int a, b;
int cost;
bool operator < (const Edge& A) const{
return cost < A.cost;
}
};
int fa[SIZE];
Edge edge[MAXSIZE];
void Init()
{
for(int i=0; i<SIZE; i++)//扩大初始化范围
{
fa[i]=i;
}
}
int Getfa(int x)
{
if(x == fa[x])
return x;
else
fa[x]=Getfa(fa[x]);
return fa[x];
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
//freopen("E:\\out.txt", "w", stdout);
#endif
int n;
while(scanf("%d", &n) != EOF && n)
{
Init();
int len=0;
while(--n>0){
char temp;
getchar();
scanf("%c", &temp);
int k;
scanf("%d", &k);
while(k-->0)
{
char ch;
scanf(" %c %d", &ch, &edge[len].cost);
edge[len].b=ch-'A';
edge[len].a=temp-'A';
len++;
}
}//n-1 lines
//printf("len:%d\n", len);
sort(edge, edge+len);
//for(int j=0;j<len;j++)
//{
// printf("%c\t%c\t%d\n", edge[j].a+'A', edge[j].b+'A', edge[j].cost);
//}
int ans=0;
for(int i=0;i<len;i++)
{
int x = Getfa(edge[i].a);
int y = Getfa(edge[i].b);
if( x!=y)
{
fa[x] = y;
ans += edge[i].cost;
//printf("-");
}
}
printf("%d\n", ans);
}
return 0;
}