題目給出離散的點,要求求出一筆把所有點都連上的最短路徑。
最多才8個點,果斷用暴力求。
用next_permutation舉出全排列,計算出路程,記錄最短路徑。
這題也可以用dfs回溯暴力,但是用最小生成樹要小心一點,最小生成樹求的是最小連通圖,而不是連成一條,不能用Kruscal,Prim算法修改一下也可以使用,改成選點時僅考慮頭尾兩點即可。
代碼:
include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std; const int maxn = 10; int p[maxn], rec[maxn], n; double sum, x[maxn], y[maxn]; double dis(double ax, double ay, double bx, double by) { double dx, dy; dx = ax - bx; dy = ay - by; return sqrt(dx * dx + dy * dy) + 16; } void solve(void) { double tmp = 0; for (int i = 0; i < n - 1; i++) tmp += dis(x[p[i]], y[p[i]], x[p[i + 1]], y[p[i + 1]]); if (tmp < sum) { sum = tmp; for (int i = 0; i < n; i++) rec[i] = p[i]; } } int main() { int cnt = 0; while (scanf("%d", &n) && n) { for (int i = 0; i < n; i++) { scanf("%lf%lf", &x[i], &y[i]); p[i] = i; } sum = 0xffffff; do { solve(); } while (next_permutation(p, p + n)); printf("**********************************************************\n"); printf("Network #%d\n", ++cnt); for (int i = 0; i < n - 1; i++) printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n", int(x[rec[i]]), int(y[rec[i]]), int(x[rec[i + 1]]), int(y[rec[i + 1]]), dis(x[rec[i]], y[rec[i]], x[rec[i + 1]], y[rec[i + 1]])); printf("Number of feet of cable required is %.2lf.\n", sum); } return 0; } #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std; const int maxn = 10; int p[maxn], rec[maxn], n; double sum, x[maxn], y[maxn]; double dis(double ax, double ay, double bx, double by) { double dx, dy; dx = ax - bx; dy = ay - by; return sqrt(dx * dx + dy * dy) + 16; } void solve(void) { double tmp = 0; for (int i = 0; i < n - 1; i++) tmp += dis(x[p[i]], y[p[i]], x[p[i + 1]], y[p[i + 1]]); if (tmp < sum) { sum = tmp; for (int i = 0; i < n; i++) rec[i] = p[i]; } } int main() { int cnt = 0; while (scanf("%d", &n) && n) { for (int i = 0; i < n; i++) { scanf("%lf%lf", &x[i], &y[i]); p[i] = i; } sum = 0xffffff; do { solve(); } while (next_permutation(p, p + n)); printf("**********************************************************\n"); printf("Network #%d\n", ++cnt); for (int i = 0; i < n - 1; i++) printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n", int(x[rec[i]]), int(y[rec[i]]), int(x[rec[i + 1]]), int(y[rec[i + 1]]), dis(x[rec[i]], y[rec[i]], x[rec[i + 1]], y[rec[i + 1]])); printf("Number of feet of cable required is %.2lf.\n", sum); } return 0; }