POJ 1251 Jungle Roads
简单,赤裸的最小生成树……
不过,有一点小障碍的地方是数据的读取!!
数据中有字符、数字掺杂这输入,整不好就读错!!
开始我用getchar()光WA,无奈又写个Readint()就可以了!
View Code
#include <stdio.h>
#include <stdlib.h>
struct Edge
{
int v,u;
int val;
}edge[200];
int com(const void *a,const void *b)
{
return (*(Edge*)a).val-(*(Edge*)b).val;
}
int ancestor[27];
void Sinit(int n)
{
for(int i=1;i<=n;i++) ancestor[i]=i;
}
int Sfind(int x)
{
if(x!=ancestor[x])
{
ancestor[x]=Sfind(ancestor[x]);
}
return ancestor[x];
}
void Sunion(int x,int y)
{
ancestor[ancestor[x]]=ancestor[y];
}
int Readint()
{
char c;
int val=0;
while((c=getchar())<'0'||c>'9');
do{val=val*10+c-'0';}while((c=getchar())>='0'&&c<='9');
return val;
}
int main()
{
int n,m;
int i,j,val,ind,mincost,cnt;
char c;
//freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
while(scanf("%d",&n) && n)
{
ind=0;
for(i=1;i<n;i++)
{
//getchar();
//scanf(" %d",&m);
m=Readint();
//getchar();
for(j=0;j<m;j++)
{
scanf("%c %d",&c,&val);getchar();
edge[ind].v=i;
edge[ind].u=c-'A'+1;
edge[ind].val=val;
++ind;
}
//getchar();
}
qsort(edge,ind,sizeof(edge[0]),com);
Sinit(n); mincost=0; cnt=0;
for(i=0;i<ind;i++)
{
if(Sfind(edge[i].v)!=Sfind(edge[i].u))
{
Sunion(edge[i].v,edge[i].u);
mincost+=edge[i].val;
if(++cnt==(n-1)) break;
}
}
// if(i==ind) printf("NOOOOOOOOOOOOOOOOOOOOOOO!\n");
printf("%d\n",mincost);
}
return 0;
}