码迷,mamicode.com
首页 > 其他好文 > 详细

【HDU1301】Jungle Roads(MST基础题)

时间:2014-07-24 22:53:33      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   re   c   

爽爆。史上个人最快MST的记录7分40s。。一次A。

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <cctype>
 7 #include <algorithm>
 8 #include <numeric>
 9 
10 #define typec int
11 using namespace std;
12 
13 const typec inf = 0xffff;
14 const int V = 35;
15 int vis[V]; typec lowc[V];
16 int Map[V][V];
17 
18 typec prim (typec cost[][V], int n) {
19     int i, j, p;
20     typec minc, res = 0;
21     memset(vis, 0, sizeof (vis));
22     vis[0] = 1;
23     for (i = 1; i < n; ++ i) lowc[i] = cost[0][i];
24     for (i = 1; i < n; ++ i) {
25         minc = inf; p = -1;
26         for (j = 0 ; j < n; ++ j) {
27             if ( 0 == vis[j] && minc > lowc[j]) {
28                 minc = lowc[j]; p = j;
29             }
30         }
31         if (inf == minc) return -1;
32         res += minc; vis[p] = 1;
33         for (j = 0 ; j < n; ++ j) {
34             if (0 == vis[j] && lowc[j] > cost[p][j]) {
35                 lowc[j] = cost[p][j];
36             }
37         }
38     }
39     return res;
40 }
41 
42 
43 int main () {
44     int n;
45     while (~scanf("%d", &n)) {
46         if (n == 0) break;
47         for (int i = 0 ; i < n; ++ i) {
48             for (int j = 0 ;j < n; ++ j) {
49                 if (i == j) Map[i][j] = 0;
50                 else Map[i][j] = inf;
51             }
52         }
53 
54         for (int i = 0 ; i < n - 1; ++ i) {
55             char s_c; int e_n;
56             cin >> s_c >> e_n;
57             for (int j = 0 ; j < e_n; ++ j) {
58                 char e_c; int w;
59                 cin >> e_c >> w;
60                 Map[s_c - A][e_c - A] = Map[e_c - A][s_c - A] = min(Map[s_c - A][e_c - A], w);
61             }
62         }
63 
64         cout << prim(Map, n) << endl;
65     }
66     return 0;
67 }

【HDU1301】Jungle Roads(MST基础题),布布扣,bubuko.com

【HDU1301】Jungle Roads(MST基础题)

标签:style   blog   color   os   io   for   re   c   

原文地址:http://www.cnblogs.com/Destiny-Gem/p/3866492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!