回溯法
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n;
bool visit[150];
int a[150];
int result[150];
double min1;
int case1 = 0;
struct point{
int x, y;
};
double sum(int a, int b){
return sqrt(a*a+b*b);
}
void dfs(double value, int cur, point p[]){
if(value>=min1){
return;
}
if(cur == n){
min1 = value;
for(int i = 0; i < n; i++){
result[i] = a[i];
}
return;
}
for(int i = 0; i < n; i++){
if(!visit[i]){
visit[i] = true;
a[cur] = i;
double num;
if(cur==0){
num = 0;
}else{
int X = a[cur];
int Y = a[cur-1];
int a1 = abs(p[X].x-p[Y].x);
int b = abs(p[X].y-p[Y].y);
num = sum(a1, b);
// cout<<X<<" "<<Y<<" "<<int(num)<<endl;
}
dfs(num+value+16, cur+1, p);
visit[i] = false;
}
}
}
void init(){
memset(a, 0, sizeof(a));
memset(visit, 0, sizeof(visit));
memset(result, 0, sizeof(result));
min1 = double(1<<30);
}
void print(point p[]){
printf("**********************************************************\n");
printf("Network #%d\n", ++case1);
double num;
for(int i = 0; i < n-1; i++){
int X = result[i];
int Y = result[i+1];
int a1 = abs(p[X].x-p[Y].x);
int b = abs(p[X].y-p[Y].y);
num = sum(a1, b);
printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2f feet.\n", p[X].x, p[X].y, p[Y].x, p[Y].y, num+16);
}
printf("Number of feet of cable required is %.2f.\n", min1-16);
}
int main(){
while(cin>>n&&n!=0){
int m = 0;
point p[150];
while(m!=n){
scanf("%d %d", &p[m].x, &p[m].y);
m++;
}
init();
dfs(0, 0, p);
print(p);
}
return 0;
}