一开始还mlt,纳闷,看了discuss才知道数据不是有规律的,他们之间可能有多个空格……所以用cin输入
View Code
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 0x3fffffff
int n,m;
struct data
{
int fr;
int to;
int w;
}edge[201];
int f[201];
bool use[201];
int cmp(data a,data b)
{
return a.w<b.w;
}
int find(int pos)
{
if(f[pos]==-1) return pos;
return f[pos]=find(f[pos]);//一定要加return
}
int un(int a,int b)
{
int fa=find(a),fb=find(b);
if(fa==fb)return 0;
f[fa]=fb;return 1;
}
void krus()
{
int i,add,j;
sort(&edge[1],&edge[m+1],cmp);
for(j=1;j<=n;j++)//使每个顶点都为-1
f[j]=-1;
add=0;
for(j=1;j<=m;j++)
{
if(un(edge[j].fr,edge[j].to)==1)
{
add+=edge[j].w;
}
}
printf("%d\n",add);
}
int main()
{
int a,b,i,x,y,add,w,count,j;
char word,w2;
while(scanf("%d",&n),n)
{
m=0;
count=1;
for(i=1;i<=n-1;i++)
{
//getchar();
//scanf("%c%d",&word,&add);
cin>>word>>add;
m+=add;
x=word-'A'+1;
for(j=1;j<=add;j++)
{
//getchar();
//scanf("%c%d",&w2,&w);
cin>>w2>>w;
y=w2-'A'+1;
edge[count].fr=x;
edge[count].to=y;
edge[count].w=w;
count++;
}
}
krus();
}
}