使用了scanf输入,之前RE,看了discuss之后才发现,行末可能有多个空格,所以要循环getchar()
附代码:
#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
int n,ans=0;
int Min,tmp;
int matrix[100][100];
int dis[100];
bool vis[100];
void prim()
{
for(int i = 0; i<n; ++i)
dis[i] = matrix[0][i];
vis[0] = 1;
for(int i = 1; i<n; ++i)
{
Min = INF;
for(int j = 1; j<n; ++j)
{
if(!vis[j]&&Min>dis[j])
{
Min = dis[j];
tmp = j;
}
}
vis[tmp] = 1;
for(int i = 0; i<n; ++i)
{
if(!vis[i]&&dis[i]>matrix[tmp][i])
dis[i] = matrix[tmp][i];
}
}
for(int i = 0; i<n; ++i)
ans += dis[i];
printf("%d\n",ans);
}
int main()
{
char v1,v2,sp;
int cnt=0,val,c;
while(scanf("%d",&n),n)
{
memset(vis,0,sizeof(vis));
ans = 0;
for(int i = 0; i<n; ++i)
{
for(int j = 1; j<n; ++j)
{
matrix[i][j] = (j==i)?0:INF;
}
}
for(int i = 0; i<n-1; ++i)
{
//行末可能有多个空格
while(1)
{
c = getchar();
if(c>='A'&&c<='Z')
break;
}
v1 = c;
scanf("%c%d",&sp,&cnt);
for(int j = 0; j<cnt; ++j)
{
scanf("%c%c%d",&sp,&v2,&val);
matrix[v1-'A'][v2-'A'] = matrix[v2-'A'][v1-'A'] = val;
}
}
prim();
}
return 0;
}