forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4.cpp
76 lines (63 loc) Β· 2.2 KB
/
4.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
72
73
74
75
76
#include <bits/stdc++.h>
using namespace std;
// λ
Έλμ κ°μ
int n;
int parent[100001]; // λΆλͺ¨ ν
μ΄λΈ μ΄κΈ°ν
// λͺ¨λ κ°μ μ λ΄μ 리μ€νΈμ, μ΅μ’
λΉμ©μ λ΄μ λ³μ
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;
// λΆλͺ¨ ν
μ΄λΈμμμ, λΆλͺ¨λ₯Ό μκΈ° μμ μΌλ‘ μ΄κΈ°ν
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
vector<pair<int, int> > x;
vector<pair<int, int> > y;
vector<pair<int, int> > z;
// λͺ¨λ λ
Έλμ λν μ’ν κ° μ
λ ₯λ°κΈ°
for (int i = 1; i <= n; i++) {
int a, b, c;
cin >> a >> b >> c;
x.push_back({a, i});
y.push_back({b, i});
z.push_back({c, i});
}
sort(x.begin(), x.end());
sort(y.begin(), y.end());
sort(z.begin(), z.end());
// μΈμ ν λ
Έλλ€λ‘λΆν° κ°μ μ 보λ₯Ό μΆμΆνμ¬ μ²λ¦¬
for (int i = 0; i < n - 1; i++) {
// λΉμ©μμΌλ‘ μ λ ¬νκΈ° μν΄μ ννμ 첫 λ²μ§Έ μμλ₯Ό λΉμ©μΌλ‘ μ€μ
edges.push_back({x[i + 1].first - x[i].first, {x[i].second, x[i + 1].second}});
edges.push_back({y[i + 1].first - y[i].first, {y[i].second, y[i + 1].second}});
edges.push_back({z[i + 1].first - z[i].first, {z[i].second, z[i + 1].second}});
}
// κ°μ μ λΉμ©μμΌλ‘ μ λ ¬
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';
}