|
Jungle RoadsTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 5516 Accepted Submission(s): 3981 Problem Description The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute Sample Input 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 Sample Output 216 30 |
AC-code:
#include<cstdio> #include<cstring> #include<algorithm> #define INF 100000 int s[30][30],n; using namespace std; void prim() { int vis[30],min,dis[30],sum,i,v,k; memset(vis,0,sizeof(vis)); for(i=1;i<n;i++) dis[i]=s[0][i]; dis[0]=0; vis[0]=1; sum=0; for(i=1;i<n;i++) { min=INF; for(v=0;v<n;v++) if(!vis[v]&&dis[v]<min) { min=dis[v]; k=v; } sum+=min; vis[k]=1; for(v=0;v<n;v++) if(!vis[v]&&dis[v]>s[k][v]) dis[v]=s[k][v]; } printf("%d\n",sum); return ; } int main() { int i,j,m,a,v,b,dis; char zh,ch; while(scanf("%d",&n),n) { getchar(); for(i=0;i<n;i++) for(j=0;j<n;j++) s[i][j]=INF; for(v=1;v<n;v++) { scanf("%c %d",&zh,&m); a=zh-65; for(i=0;i<m;i++) { scanf(" %c %d",&ch,&dis); b=ch-65; s[a][b]=s[b][a]=dis; } getchar(); } prim(); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。