-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim_heap.cpp
More file actions
94 lines (76 loc) · 1.27 KB
/
Copy pathPrim_heap.cpp
File metadata and controls
94 lines (76 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXV = 100005;
const int INF = 1e6;
struct Edge{
int from, to, dist;
};
struct HeapNode{
int u, d;
bool operator < (const HeapNode & t) const
{
return d > t.d;
}
};
vector<Edge> es;
vector<int> G[MAXV];
bool used[MAXV];
int n, m;
void init(int n, int m)
{
for(int i = 1; i <= n; i++)
G[i].clear();
es.reserve(m<<1);
es.clear();
}
void addEdge(int from, int to, int dist)
{
es.push_back((Edge){from, to, dist});
int sz = es.size();
G[from].push_back(sz - 1);
}
int prim()
{
memset(used, false, sizeof(used));
int res = 0;
priority_queue<HeapNode> que;
que.push((HeapNode){1, 0});
while(true)
{
HeapNode x;
int u = 1;
do
{
x = que.top();
que.pop();
u = x.u;
} while(used[x.u] && !que.empty());
if(used[u]) break;
used[u] = true;
res += x.d;
for(int i = 0; i < G[u].size(); i++)
{
Edge e = es[G[u][i]];
que.push((HeapNode){e.to, e.dist});
}
}
return res;
}
int main()
{
scanf("%d %d", &n, &m);
init(n, m + 1);
int a, b, c;
while(m --)
{
scanf("%d %d %d", &a, &b, &c);
addEdge(a, b, c);
addEdge(b, a, c);
}
printf("%d\n", prim());
return 0;
}