UVa 10369

Arctic Network

Solution Sketch

Build a MST using Kruskal algorithm.

The curcial observation to solving this problem is $s$ satellites can save you $s - 1$ edges in the MST!

So, while you are using Kruskal algorithm to build the MST, you also need to keep a counter of how many edges have been added into the MST. If $p - 1 - cnt = s - 1$, which means total edges in MST $p - 1$, minus $cnt$ (number of edges in MST currently), equals to the edges that can be saved $s - 1$, we can terminate the MST algorithm and output the distance of the last edge that was added.

AC Code

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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> ii;
double dist(ii a, ii b)
{
int dx = a.first - b.first;
int dy = a.second - b.second;
return sqrt(double(dx * dx + dy * dy));
}
#define N 555
struct UFDS {
int par[N];
void init()
{
memset(par, -1, sizeof(par));
}
int root(int x)
{
return par[x] < 0 ? x : par[x] = root(par[x]);
}
void merge(int x, int y)
{
x = root(x);
y = root(y);
if (x == y)
return;
if (par[x] > par[y])
swap(x, y);
par[x] += par[y];
par[y] = x;
}
} ufds;
int main()
{
int ncase;
scanf("%d", &ncase);
while (ncase--) {
int s, p;
scanf("%d %d", &s, &p);
vector<ii> inp;
for (int i = 0; i < p; i++) {
ii tmp;
scanf("%d %d", &tmp.first, &tmp.second);
inp.push_back(tmp);
}
// get distance
vector<pair<double, ii>> pt;
for (int i = 0; i < (int)inp.size(); i++)
for (int j = i + 1; j < (int)inp.size(); j++)
pt.push_back(make_pair(dist(inp[i], inp[j]), ii(i, j)));
sort(pt.begin(), pt.end());
// get MST
ufds.init();
vector<pair<double, ii>> ans;
double res = 0;
int cnt = 0;
for (int i = 0; i < (int)pt.size(); i++) {
int u = pt[i].second.first;
int v = pt[i].second.second;
double w = pt[i].first;
if (ufds.root(u) == ufds.root(v))
continue;
ufds.merge(u, v);
res = w;
cnt++;
if (p - 1 - cnt == s - 1)
break;
}
printf("%.2f\n", res);
}
return 0;
}