forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.cpp
More file actions
60 lines (50 loc) Β· 1.71 KB
/
5.cpp
File metadata and controls
60 lines (50 loc) Β· 1.71 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
#include <bits/stdc++.h>
using namespace std;
// λ
Έλμ κ°μ(V)μ κ°μ (Union μ°μ°)μ κ°μ(E)
// λ
Έλμ κ°μλ μ΅λ 100,000κ°λΌκ³ κ°μ
int v, e;
int parent[100001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// λͺ¨λ κ°μ μ λ΄μ 리μ€νΈμ, μ΅μ’
λΉμ©μ λ΄μ λ³μ
vector<pair<int, pair<int, int> > > edges;
int result = 0;
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
int findParent(int x) {
// λ£¨νΈ λ
Έλκ° μλλΌλ©΄, λ£¨νΈ λ
Έλλ₯Ό μ°Ύμ λκΉμ§ μ¬κ·μ μΌλ‘ νΈμΆ
if (x == parent[x]) return x;
return parent[x] = findParent(parent[x]);
}
// λ μμκ° μν μ§ν©μ ν©μΉκΈ°
void unionParent(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a < b) parent[b] = a;
else parent[a] = b;
}
int main(void) {
cin >> v >> e;
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= v; i++) {
parent[i] = i;
}
// λͺ¨λ κ°μ μ λν μ 보λ₯Ό μ
λ ₯ λ°κΈ°
for (int i = 0; i < e; i++) {
int a, b, cost;
cin >> a >> b >> cost;
// λΉμ©μμΌλ‘ μ λ ¬νκΈ° μν΄μ ννμ 첫 λ²μ§Έ μμλ₯Ό λΉμ©μΌλ‘ μ€μ
edges.push_back({cost, {a, b}});
}
// κ°μ μ λΉμ©μμΌλ‘ μ λ ¬
sort(edges.begin(), edges.end());
// κ°μ μ νλμ© νμΈνλ©°
for (int i = 0; i < edges.size(); i++) {
int cost = edges[i].first;
int a = edges[i].second.first;
int b = edges[i].second.second;
// μ¬μ΄ν΄μ΄ λ°μνμ§ μλ κ²½μ°μλ§ μ§ν©μ ν¬ν¨
if (findParent(a) != findParent(b)) {
unionParent(a, b);
result += cost;
}
}
cout << result << '\n';
}