USACO Cow Tours

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
/*
ID: wcr19961
PROG: cowtour
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;

typedef long long LL;
const int maxn = 160;
int x[maxn], y[maxn], p[maxn];
char s[maxn];
double len[maxn], len2[maxn];
double d[maxn][maxn];

double dis(int i, int j) {
return sqrt(double(x[i] - x[j]) * (x[i] - x[j]) + double(y[i] - y[j]) * (y[i] - y[j]));
}

int find(int x) {
return x == p[x] ? x : p[x] = find(p[x]);
}

int main() {
freopen("cowtour.in", "r", stdin);
freopen("cowtour.out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
p[i] = i;
scanf("%d%d", &x[i], &y[i]);
}
for (int i = 1; i <= n; ++i) {
scanf("%s", s + 1);
for (int j = 1; j < i; ++j) {
if (s[j] == '1') {
p[find(i)] = p[find(j)];
d[i][j] = d[j][i] = dis(i, j);
} else {
d[i][j] = d[j][i] = 1e9;
}
}
}
for (int k = 1; k <= n; ++k) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
for (int i = 1; i <= n; ++i) {
find(i);
for (int j = 1; j < i; ++j) {
if (p[i] == p[j]) {
len[i] = max(len[i], d[i][j]);
len[j] = max(len[j], d[i][j]);
}
}
len2[p[i]] = max(len2[p[i]], len[i]);
}
double ans = 1e9;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j < i; ++j) {
if (p[i] != p[j]) {
ans = min(ans, len[i] + len[j] + dis(i, j));
}
}
}
for (int i = 1; i <= n; ++i) {
ans = max(ans, len2[i]);
}
printf("%.6f\n", ans);
return 0;
}