hdu 1863 畅通工程 (prim)

畅通工程
Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 37969    Accepted Submission(s): 16915

Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
 
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
 
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
 
Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
 
Sample Output
3
?
 

C/C++:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <stack>
 7 #include <set>
 8 #include <map>
 9 #include <queue>
10 #include <climits>
11 #include <bitset>
12 #define eps 1e-6
13 using namespace std;
14 
15 int n, m, my_map[110][110];
16 
17 int prim()
18 {
19     /**
20         Initialize
21     */
22     int my_pos = 1, my_book[110] = {0, 1}, my_distance[110], my_ans = 0;
23     for (int i = 2; i <= m; ++ i)
24         my_distance[i] = my_map[my_pos][i];
25 
26     for (int i = 1; i < m; ++ i)
27     {
28         int my_min = INT_MAX;
29         for (int j = 2; j <= m; ++ j)
30         {
31             if (my_book[j] || my_distance[j] >= my_min) continue;
32             my_min = my_distance[j];
33             my_pos = j;
34         }
35         if (my_min == INT_MAX) return 0; // Can't reach
36 
37         my_book[my_pos] = 1;
38         my_ans += my_min;
39 
40         for (int j = 2; j <= m; ++ j)
41         {
42             if (my_map[j][my_pos] < my_distance[j])
43                 my_distance[j] = my_map[j][my_pos];
44         }
45     }
46 
47     return my_ans;
48 }
49 
50 int main()
51 {
52     ios::sync_with_stdio(false);
53 
54     while(scanf("%d%d", &n, &m), n)
55     {
56         /**
57             Initialize
58         */
59         for (int i = 1; i <= m; ++ i)
60             for (int j = i; j <= m; ++ j)
61                 my_map[i][j] = my_map[j][i] = INT_MAX;
62 
63         /**
64             Date Input
65         */
66         for (int i = 1; i <= n; ++ i)
67         {
68             int a, b, a_b_distance;
69             scanf("%d%d%d", &a, &b, &a_b_distance);
70             my_map[a][b] = my_map[b][a] = a_b_distance;
71         }
72 
73         /**
74             Process
75         */
76         int my_temp = prim();
77         if (my_temp)
78             printf("%d\n", my_temp);
79         else
80             printf("?\n");
81     }
82     return 0;
83 }

猜你喜欢

转载自www.cnblogs.com/GetcharZp/p/9415942.html
今日推荐