forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroids.cpp
102 lines (79 loc) · 1.7 KB
/
androids.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct planet {
ll x, y, z, n;
};
struct edge {
ll n1, n2, w;
};
edge build(planet p1, planet p2) {
edge e = {p1.n, p2.n,
min({abs(p1.x - p2.x),
abs(p1.y - p2.y),
abs(p1.z - p2.z)})};
return e;
}
bool cmpx(planet lhs, planet rhs) {
return lhs.x < rhs.x;
}
bool cmpy(planet lhs, planet rhs) {
return lhs.y < rhs.y;
}
bool cmpz(planet lhs, planet rhs) {
return lhs.z < rhs.z;
}
bool cmpedge(edge lhs, edge rhs) {
return lhs.w < rhs.w;
}
ll find(vector<ll>& v, ll a) {
if(v[a] == -1) {
return a;
}
v[a] = find(v, v[a]);
return v[a];
}
void join(vector<ll>& v, ll a, ll b) {
a = find(v, a);
b = find(v, b);
if(a == b) {
return;
}
v[a] = b;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
ll n;
cin >> n;
vector<planet> v(n);
ll p = 0;
for(auto& i : v) {
cin >> i.x >> i.y >> i.z;
i.n = p++;
}
vector<edge> edges;
sort(v.begin(), v.end(), cmpx);
for(ll i = 1; i < n; i++) {
edges.push_back(build(v[i-1], v[i]));
}
sort(v.begin(), v.end(), cmpy);
for(ll i = 1; i < n; i++) {
edges.push_back(build(v[i-1], v[i]));
}
sort(v.begin(), v.end(), cmpz);
for(ll i = 1; i < n; i++) {
edges.push_back(build(v[i-1], v[i]));
}
// min span tree
vector<ll> d(n, -1);
sort(edges.begin(), edges.end(), cmpedge);
ll total = 0;
for(auto i : edges) {
if(find(d, i.n1) != find(d, i.n2)) {
join(d, i.n1, i.n2);
total += i.w;
}
}
cout << total << endl;
}