A discrete vertex is given, and a shortest path connecting all vertices is required.
A maximum of 8 points, decisive use of violence.
Use next_permutation to list all rows, calculate the outbound route, and record the shortest path.
This problem can also be traced back to brute force with dfs, but be careful when using the minimal spanning tree. The minimum spanning tree is used to find the least connected graph, instead of connecting one. Kruscal cannot be used, you can also use the Prim algorithm to modify it. You only need to consider the first and last two points when you change it to the selected point.
Code:
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;}