-
Notifications
You must be signed in to change notification settings - Fork 0
/
1197_MinimumSpanningTree.cpp
71 lines (53 loc) · 1.09 KB
/
1197_MinimumSpanningTree.cpp
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
#include<iostream>
#include<vector>
#include<queue>
#define MAX 10001
using namespace std;
using pii = pair<int, int>;
// ascending, minheap
struct compare{
bool operator()(pii node1, pii node2){
if(node1.first == node2.first)
return node1.second > node2. second;
return node1.first > node2.first;
}
};
// MST
// PRIM
// O(NlogN)
bool visited[MAX];
vector<pii> graph[MAX];
int MST(int V){
int ans = 0;
priority_queue<pii, vector<pii>, compare> hq; // {edgecost, node}
fill_n(visited, MAX, false);
hq.push({0, V});
while(V){
pii p = hq.top();
int node = p.second, cost = p.first;
hq.pop();
if(visited[node])
continue;
ans += cost;
visited[node] = true;
for(int i = 0; i<graph[node].size(); i++){
int child = graph[node][i].first, edge = graph[node][i].second;
if(!visited[child])
hq.push({edge, child});
}
V--;
}
return ans;
}
int main() {
int V, E;
cin >> V >> E;
while(E--){
int node1, node2, w;
cin >> node1 >> node2 >> w;
graph[node1].push_back({node2, w});
graph[node2].push_back({node1, w});
}
cout << MST(V) << "\n";
return 0;
}