直接用next_permutation函数排列,再进行暴力循环就好了。
#include "stdio.h" #include "math.h" #include<algorithm> using namespace std; int b[10],x[10],y[10],n,a[10]; double sum,temp,minx; double len(int x1,int y1,int x2,int y2) { double t; t=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); return sqrt(t)+16; } void fun() { int i; sum=0; for(i=0;i<n-1;i++) sum+=len(x[b[i]],y[b[i]],x[b[i+1]],y[b[i+1]]); if(sum<minx){ minx=sum; for(i=0;i<n;i++) a[i]=b[i]; } } int main() { int i,cas=0; while(~scanf("%d",&n)) { if(n==0) break; for(i=0;i<n;i++) { scanf("%d%d",&x[i],&y[i]); b[i]=i; } minx=99999999; do{fun();}while(next_permutation(b,b+n)); printf("********************************************************** "); printf("Network #%d ",++cas); for(i=0;i<n-1;i++)
printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2f feet. ",x[a[i]],y[a[i]],x[a[i+1]],y[a[i+1]],len(x[a[i]],y[a[i]],x[a[i+1]],y[a[i+1]])); printf("Number of feet of cable required is %.2f. ",minx); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/