题目链接地址:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1271
很少发题解,但是这是自己切掉的第一个final题目,小小成就感。
题目解法很多,经典的Voronoi图,但是比较麻烦。
抽象后即为求两点之间的最短路,用floyd算法预处理即可。关键是求给定路径长度(两个城市间最少中转信号站的个数),可以确定,当离a, b两个城市距离最近的信号站为一个时,距离 d(a, b) 为零,如果不为零,两城市之间的路径长度为:d(a, b) = d(a, c) + d(c, b) [ c 为a,b的中点 ],不断二分,直到两个坐标所属信号站相同——说明距离为零——或者 两个坐标的距离小于eps(一个精度,去1e-6足以)——距离为1。
代码:
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const int MAXN = 55; const int inf = 0x1f7f7f7f; const double eps = 1e-6; int n, m, r, q; int g[MAXN][MAXN]; double sx[MAXN], sy[MAXN], cx[MAXN], cy[MAXN]; double dis(double x1, double y1, double x2, double y2) { return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } void init() { for (int i=1; i<=n; i++) scanf("%lf %lf", &sx[i], &sy[i]); for (int i=1; i<=m; i++) scanf("%lf %lf", &cx[i], &cy[i]); for (int i=1; i<=m; i++) g[i][i] = 0; for (int i=1; i<m; i++) for (int j=i+1; j<=m; j++) g[i][j] = g[j][i] = inf; } int belong(int x, int y) { int ret; double tmp, mind = inf; for (int i=1; i<=n; i++) { tmp = dis(x, y, sx[i], sy[i]); if (tmp < mind) mind = tmp, ret = i; } return ret; } int get_dist(double x1, double y1, double x2, double y2) { int a = belong(x1, y1), b = belong(x2, y2); if (a == b) return 0; if (dis(x1, y1, x2, y2) < eps) return 1; double x = (x1 + x2) / 2.0, y = (y1 + y2) / 2.0; return get_dist(x1, y1, x, y) + get_dist(x, y, x2, y2); } void work() { int a, b; while (r--) { scanf("%d%d", &a, &b); g[a][b] = g[b][a] = get_dist(cx[a], cy[a], cx[b], cy[b]); } for (int k=1; k<=m; k++) for (int i=1; i<=m; i++) if (i != k) { for (int j=1; j<=m; j++) if (i != j && k != j && g[i][k] + g[k][j] < g[i][j]) g[i][j] = g[i][k] + g[k][j]; } while (q--) { scanf("%d %d", &a, &b); if (g[a][b] >= inf) printf("Impossible\n"); else printf("%d\n", g[a][b]); } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif // ONLINE_JUDGE int cas = 1; while (scanf("%d%d%d%d", &n, &m, &r, &q) == 4 && (n+m+r+q)) { printf("Case %d:\n", cas++); init(); work(); } return 0; }