【POJ】1251 Jungle Roads

题目链接:http://poj.org/problem?id=1251

题意:n个村庄字母标号,每个字母后跟m个字母,表示该字母到mi的距离。求构建所有村庄道路的最短距离。

题解:最小生成树裸题。注意输入。

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 const int maxn = 30;
 6 const int inf = 0x3f3f3f3f;
 7 int mp[maxn][maxn];
 8 int dis[maxn];
 9 bool vis[maxn];
10 int n;
11 int prim(){
12     memset(dis,0x3f,sizeof(dis));
13     memset(vis,0,sizeof(vis)); 
14     int ans = 0;
15     dis[1] = 0;
16     while(1){
17         int k = 0;
18         for(int j = 1; j <= n;j++){
19             if(!vis[j] && dis[j] < dis[k])
20                 k = j; 
21         } 
22         if(!k) break;
23         vis[k] = 1; 
24         ans += dis[k];
25         for(int j = 1; j <= n;j++){
26             if(dis[j] > mp[k][j]){
27                 dis[j] = mp[k][j];
28             }
29 
30         }
31     }
32     return ans;
33 }
34 int main(){
35     int m, w;
36     char ch1,ch2;
37     while(cin >> n && n){
38         memset(mp,0x3f,sizeof(mp));
39         for(int i = 0; i < n; i++)
40             mp[i][i] = 0;
41         for(int i = 1; i < n; i++){
42             cin>>ch1>>m;
43             int s = ch1 - 'A' + 1;
44             while(m--){
45                 cin>>ch2>>w;
46                 int t = ch2 - 'A' + 1;
47                 mp[s][t] = mp[t][s] = w;
48             }
49         }
50         cout<<prim()<<endl;
51     }
52     return 0;
53 }

猜你喜欢

转载自www.cnblogs.com/Asumi/p/9749074.html