forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreckles.cpp
93 lines (75 loc) · 1.76 KB
/
freckles.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
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
typedef long double ld;
struct edge {
int n1;
int n2;
ld dist;
};
ld dist(pair<ld, ld> p1, pair<ld, ld> p2) {
return sqrt(pow(p1.first - p2.first, 2) + pow(p1.second - p2.second, 2));
}
bool cmp(edge lhs, edge rhs) {
return lhs.dist < rhs.dist;
}
int find(vector<int>& disjoint, int a) {
if(disjoint[a] == -1) {
return a;
}
disjoint[a] = find(disjoint, disjoint[a]);
return disjoint[a];
}
void join(vector<int>& disjoint, int a, int b) {
a = find(disjoint, a);
b = find(disjoint, b);
if(a == b) {
return;
}
disjoint[a] = b;
}
int main() {
int cases;
cin >> cases;
bool first = true;
while(cases--) {
// Print extra endls
if(first) {
first = false;
}
else {
cout << endl;
}
// Take in input
int n;
cin >> n;
vector<pair<ld, ld>> v(n);
for(auto& i : v) {
cin >> i.first >> i.second;
}
// Build edge list
vector<edge> edges;
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
edge e = {i, j, dist(v[i], v[j])};
edges.push_back(e);
}
}
// Sort edges
sort(edges.begin(), edges.end(), cmp);
// Find minimum edges
ld total = 0;
vector<int> disjoint(n, -1);
for(auto& i : edges) {
if(find(disjoint, i.n1) != find(disjoint, i.n2)) {
total += i.dist;
join(disjoint, i.n1, i.n2);
}
}
cout << fixed;
cout.precision(2);
cout << total << endl;
}
}