题意:给出不超过8个点的坐标,要求所铺的电路最短
思路:因为点的数量最多不会超过8个,所以可以直接暴力搜索。利用全排列,将所有可能的情况都计算一次,更新最短路径。
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
int b[8], c[8];
struct node{
int x, y;
}a[10];
double lenth(double x1, double y1, double x2, double y2){
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) + 16;
}
int main(){
int n, t = 0;
double len, sum, min;
while (scanf("%d", &n) && n){
min = 100000;
for(int i = 0; i < n; i++){
scanf("%d %d", &a[i].x, &a[i].y);
b[i] = i;
}
do {
sum = 0;
for(int i = 0; i < n - 1; i++){
len = lenth(a[b[i]].x, a[b[i]].y, a[b[i + 1]].x, a[b[i + 1]].y);
sum += len;
}
if (sum < min){
min = sum;
for(int i = 0; i < n; i++)
c[i] = b[i];
}
} while (next_permutation(b, b + n));
printf("**********************************************************\n");
printf("Network #%d\n", ++t);
for(int i = 0; i < n - 1; i++){
len = lenth(a[c[i]].x, a[c[i]].y, a[c[i + 1]].x, a[c[i + 1]].y);
printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n", a[c[i]].x, a[c[i]].y, a[c[i + 1]].x, a[c[i + 1]].y, len);
}
printf("Number of feet of cable required is %.2lf.\n", min);
}
return 0;
}