2014-07-14 16:24:28
题意&思路:这题基本和求最小生成树总和一样,但由于数据量较小,可以直接next_permutation 全排列来做。(原来MST也可以暴力,真是涨姿势)
1 #include <cstdio> 2 #include <iostream> 3 #include <cmath> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 8 struct Node{ 9 double x,y; 10 }; 11 12 int n; 13 14 double Dis(double x1,double y1,double x2,double y2){ 15 return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); 16 } 17 18 int main(){ 19 int i,j,Case = 0; 20 while(scanf("%d",&n) == 1 && n){ 21 Node node[10]; 22 int s[10],ans[10]; 23 double tmin = 0; 24 for(i = 1; i <= n; ++i){ 25 scanf("%lf %lf",&node[i].x,&node[i].y); 26 if(i != 1) 27 tmin += Dis(node[i - 1].x,node[i - 1].y,node[i].x,node[i].y); 28 s[i] = i; 29 } 30 memcpy(ans,s,sizeof(s)); 31 double tsum; 32 while(next_permutation(s + 1,s + n + 1)){ 33 tsum = 0; 34 for(i = 2; i <= n; ++i) 35 tsum += Dis(node[s[i - 1]].x,node[s[i - 1]].y,node[s[i]].x,node[s[i]].y); 36 if(tsum < tmin){ 37 tmin = tsum; 38 memcpy(ans,s,sizeof(s)); 39 } 40 } 41 printf("**********************************************************\n"); 42 printf("Network #%d\n",++Case); 43 for(i = 2; i <= n; ++i) 44 printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2lf feet.\n",(int)node[ans[i - 1]].x, 45 (int)node[ans[i - 1]].y,(int)node[ans[i]].x,(int)node[ans[i]].y,16.0 + Dis(node[ans[i - 1]].x,node[ans[i - 1]].y,node[ans[i]].x,node[ans[i]].y)); 46 printf("Number of feet of cable required is %.2lf.\n",tmin + (n - 1) * 16.0); 47 } 48 return 0; 49 }