HDOJ 1879 Prim实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ 1879 Prim实现相关的知识,希望对你有一定的参考价值。

调试中遇到的困难主要在于building队列的维护。不能简单地将新增edge加入queue,需要对其方向进行处理。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <queue>
 4 #include <cstring>
 5 
 6 using namespace std;
 7 
 8 #define N 100
 9 
10 struct road{
11     int begin;
12     int end;
13     int value;
14 };
15 
16 bool operator < (road a, road b){
17     return a.value > b.value;
18 }
19 
20 int main(){
21     int n;
22     while (scanf("%d", &n), n != 0){
23         int num = n*(n-1)/2;
24         int total_value = 0;
25         int count = 1;
26         road roads[num];
27         priority_queue<road> roads_building;
28         bool roads_outqueue[num];
29         bool linked[n];
30         memset(roads_outqueue, true, sizeof(roads_outqueue));
31         memset(linked, false, sizeof(linked));
32         for (int i = 0; i < num; i++){
33             int built;
34             scanf("%d %d %d %d", &roads[i].begin, &roads[i].end, &roads[i].value, &built);
35             if (built == 1)
36                 roads[i].value = 0;
37         }
38         for (int i = 0; i < num; i++)
39             if (roads[i].begin == 1){
40                 roads_building.push(roads[i]);
41                 roads_outqueue[i] = false;
42             }
43         linked[0] = true;
44         while (count < n){
45             road top = roads_building.top();
46             roads_building.pop();
47             if (not linked[top.end - 1]){
48                 linked[top.end - 1] = true;
49                 total_value += top.value;
50                 count += 1;
51                 for (int i = 0; i < num; i++)
52                     if (roads_outqueue[i]){
53                         if (roads[i].begin == top.end){
54                             roads_building.push(roads[i]);
55                             roads_outqueue[i] = false;
56                         }
57                         else if (roads[i].end == top.end){
58                             road temp;
59                             temp.begin = roads[i].end;
60                             temp.end = roads[i].begin;
61                             temp.value = roads[i].value;
62                             roads_building.push(temp);
63                             roads_outqueue[i] = false;
64                         }
65                     }
66             }
67         }
68         printf("%d\n", total_value);
69     }
70     return 0;
71 }

 

以上是关于HDOJ 1879 Prim实现的主要内容,如果未能解决你的问题,请参考以下文章

hdoj1879 继续畅通工程(Prime || Kruskal)

HDoj-1233-还是畅通project-prim算法

最小生成树算法

HDU 1879 继续畅通工程

Prim算法的python实现

C++ 实现无向图的最小生成树Prim算法(附完整代码)