注意初始化的cost矩阵,cost[i][i]=0,相互的那个也要初始化

/* ***********************************************
Author :PeterBishop
Created Time :Tue 19 Feb 2019 22:52:00 CST
File Name :t.cpp
Origin :P O J 1251
************************************************ */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <set>
#include <map>
int N;
using namespace std;
const int MAXN=30;
const int INF=0x3f3f3f3f;
bool vis[MAXN];
int lowc[MAXN];
int prim(int cost[][MAXN],int n){
int ans=0;
memset(vis,false,sizeof(vis));
vis[0]=true;
for(int i=1;i<n;i++)
lowc[i]=cost[0][i];
for(int i=1;i<n;i++){
int minc=INF;
int p=-1;
for(int j=0;j<n;j++)
if(!vis[j]&&minc>lowc[j]){
minc=lowc[j];
p=j;
}
if(minc==INF)
return -1;
ans+=minc;
vis[p]=true;
for(int j=0;j<n;j++)
if(!vis[j]&&lowc[j]>cost[p][j])
lowc[j]=cost[p][j];
}
return ans;
}
int main()
{
//freopen("out.txt","w",stdout);
freopen("in.txt","r",stdin);
while(cin>>N){
if(N==0)
break;
int cost[MAXN][MAXN];
for(int i=0;i<MAXN;i++)
for(int j=0;j<MAXN;j++)
cost[i][j]=i==j?0:INF;
for(int i=0;i<N-1;i++){
char a;
int k;
cin>>a>>k;
for(int j=0;j<k;j++){
char x;
int m;
cin>>x>>m;
cost[a-'A'][x-'A']=cost[x-'A'][a-'A']=m;
}
}
cout<<prim(cost,N)<<endl;



}



return 0;
}