Question: give you the plane position of n computers and ask for the minimum length of the network cable required for connecting them to a linear network.
Analysis: Search and enumeration.
Because the data size is small, the full arrangement of all computers is enumerated. Each arrangement corresponds to a connection method.
Enumerate all the connection methods and find the smallest output path.
Note: We thought it was the shortest path or the shortest tree similarity (⊙ _ ⊙ ).
#include <iostream>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;typedef struct pnode{int x,y;}point;point P[10];double dist(point a, point b){return sqrt(0.0+(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y))+16.0;}int link[40320][10];int l_count;int used[10],save[10];void dfs(int d, int n){if (d == n) {for (int i = 0 ; i < n ; ++ i)link[l_count][i] = save[i];l_count ++;return;}for (int i = 0 ; i < n ; ++ i)if (!used[i]) {used[i] = 1;save[d] = i;dfs(d+1, n);used[i] = 0;}}int main(){int n,t = 1;while (~scanf("%d",&n) && n) {for (int i = 0 ; i < n ; ++ i)scanf("%d%d",&P[i].x,&P[i].y);for (int i = 0 ; i < n ; ++ i)used[i] = 0;l_count = 0;dfs(0, n);double min = 3000.0;int spa = 0;for (int i = 0 ; i < l_count ; ++ i) {double sum = 0.0;for (int j = 1 ; j < n ; ++ j)sum += dist(P[link[i][j-1]], P[link[i][j]]);if (sum < min) {min = sum;spa = i;}}printf("**********************************************************\n");printf("Network #%d\n",t ++);for (int j = 1 ; j < n ; ++ j)printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n", P[link[spa][j-1]].x,P[link[spa][j-1]].y,P[link[spa][j]].x,P[link[spa][j]].y,dist(P[link[spa][j-1]], P[link[spa][j]]));printf("Number of feet of cable required is %.2lf.\n",min);}return 0;}
Ultraviolet A 216-getting in line