题意:
整个图由若干个连通分量构成,在图中加一条边,使两个原本不连通的分量连通,得到一个新的连通分量。
要求,使得新的连通分量的直径最小。直径 = max{两两点对之间最短距离}.
求这样的最小直径。
思路:
考虑两块不连通的 G1 与 G2,在它们之间 u v 间新加一条边得到新的 G,那么 G 的直径必然是
max{ G1的直径, G2的直径,dist(u, v) + u在G中的最远距离 + v在G中的最远距离} ……(*)
这三者的最大值。
故
floyd找出图中两两点对之间的最短距离;
对每个点,找出它在图中和其余点之间的最远距离;
对每个连通分量(并查集),找出它的直径;
最后枚举两两点对,如果不在同一个连通分量中,加边,并按上面的式(*)计算即可
(十分神奇,两个多月以前怎么都写不对,刚刚重写了一遍一发过0 0)
AC代码如下:
/*
TASK:cowtour
ID:fan_0111
LANG:C++
*/
#include <cmath>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct Point { int x, y; }p[160];
char s[160];
double dist[160][160], far[160], in[160];
int fa[160], group[160];
map<int, int> m;
vector<int> v[160];
double dis(Point a, Point b) {
int dx = abs(b.x - a.x), dy = abs(b.y - a.y);
return sqrt(dx * dx + dy * dy);
}
int findfa(int x) {
return fa[x] == x ? x : fa[x] = findfa(fa[x]);
}
void join(int a, int b) {
int fa1 = findfa(a), fa2 = findfa(b);
fa[fa2] = fa1;
}
int main() {
freopen("cowtour.in", "r", stdin);
freopen("cowtour.out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &p[i].x, &p[i].y);
}
for (int i = 0; i < n; ++i) fa[i] = i;
for (int i = 0; i < n; ++i) {
scanf("%s", s);
for (int j = 0; j < strlen(s); ++j) {
if (s[j] == '1') {
dist[j][i] = dist[i][j] = dis(p[i], p[j]);
join(i, j);
}
}
}
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (dist[i][k] != 0 && dist[k][j] != 0 && (dist[i][j] == 0 || dist[i][j] > dist[i][k] + dist[k][j])) {
dist[j][i] = dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int tot = 0;
for (int i = 0; i < n; ++i) {
if (!m.count(findfa(i))) {
m.insert(make_pair(findfa(i), tot));
}
tot = m[findfa(i)];
v[tot].push_back(i);
group[i] = tot++;
}
for (int i = 0; i < n; ++i) {
double maxD = 0;
for (int j = 0; j < n; ++j) {
maxD = dist[i][j] > maxD ? dist[i][j] : maxD;
}
far[i] = maxD;
}
for (int i = 0; i < tot; ++i) {
double maxD = 0;
for (int j = 0; j < v[i].size(); ++j) {
maxD = far[v[i][j]] > maxD ? far[v[i][j]] : maxD;
}
in[i] = maxD;
}
double ans = 1e9;
for (int i = 0; i < n; ++i) {
double maxD = 0;
for (int j = 0; j < n; ++j) {
if (findfa(i) == findfa(j)) continue;
maxD = max(in[group[i]], in[group[j]]);
double cro = far[i] + far[j] + dis(p[i], p[j]);
maxD = cro > maxD ? cro : maxD;
ans = maxD < ans ? maxD : ans;
}
}
printf("%.6lf\n", ans);
// for (int i = 0; i < n; ++i) {
// for (int j = 0; j < n; ++j) {
// printf("%lf ", dist[i][j]);
// }
// printf("\n");
// }
// for (int i = 0; i < n; ++i) printf("%d ", findfa(i)); printf("\n");
// for (int i = 0; i < n; ++i) printf("%lf ", far[i]); printf("\n");
// for (int i = 0; i < tot; ++i) {
// for (int j = 0; j < v[i].size(); ++j) {
// printf("%d ", v[i][j]);
// }
// printf("\n");
// printf("%lf ", in[i]); printf("\n");
// }
return 0;
}