-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaekjoon_1197.cpp
49 lines (36 loc) · 1.08 KB
/
baekjoon_1197.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
#include <bits/stdc++.h>
using namespace std;
class NodeConn {
public:
NodeConn(int a, int b, int c): from(a), to(b), weight(c) {}
bool operator > (const NodeConn& op) const { return this->weight > op.weight; }
bool operator < (const NodeConn& op) const { return this->weight < op.weight; }
int from, to, weight;
};
int V, E, A, B, C, ans, parent[10001];
priority_queue<NodeConn, vector<NodeConn>, greater<NodeConn>> pq;
int _find(int now) {
if(!parent[now] || parent[now] == now) return (parent[now] = now);
return (parent[now] = _find(parent[now]));
}
bool _union(int a, int b) {
int pa = _find(a);
int pb = _find(b);
if(pa == pb) return true;
parent[pb] = pa;
return false;
}
int main() { cin.tie(0); cout.tie(0)->sync_with_stdio(0);
cin >> V >> E;
while(E--) {
cin >> A >> B >> C;
pq.push(NodeConn(A, B, C));
}
while(!pq.empty()) {
auto now = pq.top(); pq.pop();
if(_union(now.from, now.to)) continue;
ans += now.weight;
}
cout << ans;
return 0;
}