首页 > 其他 > 详细

【HDU1102】Constructing Roads(MST基础题)

时间:2014-07-22 23:29:57      阅读:357      评论:0      收藏:0      [点我收藏+]

最小生成树水题。prim一次AC

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cstdio>
 5 #include <cctype>
 6 #include <cmath>
 7 #include <algorithm>
 8 #include <numeric>
 9 
10 #define typec int
11 using namespace std;
12 
13 const int V = 105;
14 const int inf = 0xffff;
15 int vis[V]; typec lowc[V];
16 int Map[105][105];
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 int main () {
43     //cout << inf <<endl;
44     int n;
45     while (cin >> n) {
46         for (int i = 0 ; i < n; ++ i) {
47             for (int j = 0 ; j < n; ++ j) {
48                 scanf("%d", &Map[i][j]);
49             }
50         }
51         int ok_line; cin >> ok_line;
52         for (int i = 0; i < ok_line; ++ i) {
53             int s, e;
54             scanf("%d%d", &s, &e);
55             Map[s - 1][e - 1] = Map[e - 1][s - 1] = 0;
56         }
57         cout << prim(Map, n) << endl;
58     }
59     return 0;
60 }

【HDU1102】Constructing Roads(MST基础题),布布扣,bubuko.com

【HDU1102】Constructing Roads(MST基础题)

原文:http://www.cnblogs.com/Destiny-Gem/p/3861435.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!