标签:
#include <iostream> #include<cstdio> #include<cstring> #include<climits> #include<cmath> using namespace std; int i,j,n,m,sum; bool vis[55]; int dis[55],mp[55][55]; void prim() { for(int i=1;i<n;i++) { double minn=INT_MAX; int k; for(int j=1;j<=n;j++) if (!vis[j] && dis[j]<minn) { k=j; minn=dis[j]; } vis[k]=1; sum+=minn; for(int j=1;j<=n;j++) if (!vis[j] && mp[k][j]<dis[j]) dis[j]=mp[k][j]; } return; } int main() { while(scanf("%d",&n) && n) { memset(vis,0,sizeof(vis)); for(i=1;i<=n;i++) for(j=1;j<=n;j++) mp[i][j]=INT_MAX; for(i=1;i<n;i++) { char ch; scanf("%s %d",&ch,&m); int u=ch-‘A‘+1,d; for(j=1;j<=m;j++) { scanf("%s %d",&ch,&d); int v=ch-‘A‘+1; mp[u][v]=d; mp[v][u]=d; } } sum=0; vis[1]=1; for(i=1;i<=n;i++) dis[i]=mp[1][i]; prim(); printf("%d\n",sum); } return 0; }
9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0
216 30
HDU-1301 Jungle Roads(最小生成树[Prim])
标签:
原文地址:http://www.cnblogs.com/stepping/p/5723160.html