forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3.cpp
More file actions
61 lines (51 loc) Β· 1.7 KB
/
3.cpp
File metadata and controls
61 lines (51 loc) Β· 1.7 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
#include <bits/stdc++.h>
using namespace std;
// λ
Έλμ κ°μμ κ°μ μ κ°μ
int n, m;
int parent[200001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// λͺ¨λ κ°μ μ λ΄μ 리μ€νΈμ, μ΅μ’
λΉμ©μ λ΄μ λ³μ
vector<pair<int, pair<int, int> > > edges;
int result;
// νΉμ μμκ° μν μ§ν©μ μ°ΎκΈ°
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 >> n >> m;
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
// λͺ¨λ κ°μ μ λν μ 보λ₯Ό μ
λ ₯λ°κΈ°
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
// λΉμ©μμΌλ‘ μ λ ¬νκΈ° μν΄μ ννμ 첫 λ²μ§Έ μμλ₯Ό λΉμ©μΌλ‘ μ€μ
edges.push_back({z, {x, y}});
}
// κ°μ μ λΉμ©μμΌλ‘ μ λ ¬
sort(edges.begin(), edges.end());
int total = 0; // μ 체 κ°λ‘λ± λΉμ©
// κ°μ μ νλμ© νμΈνλ©°
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;
total += cost;
// μ¬μ΄ν΄μ΄ λ°μνμ§ μλ κ²½μ°μλ§ μ§ν©μ ν¬ν¨
if (findParent(a) != findParent(b)) {
unionParent(a, b);
result += cost;
}
}
cout << total - result << '\n';
}