-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoad_Reparation.cpp
More file actions
85 lines (64 loc) · 1.45 KB
/
Road_Reparation.cpp
File metadata and controls
85 lines (64 loc) · 1.45 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
/*
The goal is to find a minmum total cost path that connects ALL the cities
aka. build the Minimum Spanning Tree and return its cost
Kruskal's Algorithm with Union Find.
sort(edges.begin(), edges.end()) gives Runtime error for the last test case.
priority queue doesn't
*/
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef tuple<int, int, long long> t3;
unordered_map<int, vector<int>> adj;
vector<int> parent;
vector<int> treesize;
int p_prev = -1;
void unite(int p, int b) {
parent[b] = p;
treesize[p]++;
for (int next : adj[b]) {
if (parent[next] == p_prev) {
parent[next] = p;
unite(p, next);
}
}
}
int main() {
int n, m;
cin >> n >> m;
auto comp = [](t3 & a, t3 & b) {
auto [a1, a2, a3] = a;
auto [b1, b2, b3] = b;
return a3 >= b3;
};
priority_queue<t3, vector<t3>, decltype(comp)> pq(comp);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
pq.push({a, b, c});
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int i = 0; i <= n; i++){
parent.push_back(i);
treesize.push_back(1);
}
long long ans = 0;
while(!pq.empty()){
auto [a, b, cost] = pq.top();
pq.pop();
if (parent[a] == parent[b]) continue;
ans += cost;
if (treesize[parent[a]] > treesize[parent[b]]) {
p_prev = parent[b];
unite(parent[a], b);
} else {
p_prev = parent[a];
unite(parent[b], a);
}
}
if (treesize[parent[1]] != n)
cout << "IMPOSSIBLE";
else cout << ans;
}