题目链接:http://poj.org/problem?id=1251
字符用%s好了,方便一点。
#include <stdio.h> #include <string.h> #define INF 0x3f3f3f3f int maps[305][305]; bool vis[305]; int dis[305]; int n; int Prim() { memset(vis,false,sizeof(vis)); for(int i=1; i<=n; i++) dis[i] = INF; int ans=0; dis[1] = 0; for(int i=1; i<=n; i++) { int tmp = INF,k=0; for(int j=1; j<=n; j++) { if(!vis[j]&&dis[j]<tmp) { tmp = dis[j]; k=j; } } vis[k] = true; ans+=tmp; for(int i=1; i<=n; i++) { if(!vis[i]&&dis[i]>maps[k][i]) dis[i] = maps[k][i]; } } return ans; } int main() { while(scanf("%d",&n),n) { for(int i=0; i<=n; i++) { for(int j=0; j<=n; j++) if(i==j) maps[i][j]=0; else maps[i][j] = INF; } for(int i=0; i<n-1; i++) { int t; char a[2],b[2]; scanf("%s%d",a,&t); for(int j=0; j<t; j++) { int dist; scanf("%s%d",b,&dist); maps[a[0]-'A'+1][b[0]-'A'+1] = maps[b[0]-'A'+1][a[0]-'A'+1] = dist; } } printf("%d ",Prim()); } return 0; }