题目链接:UVa 216 - Getting in Line
挺简单的一道回溯题,可是我做了好久啊啊啊啊啊啊啊。还是不熟练啊啊啊啊啊。
#include <iostream>
#include <cmath>
#include <iomanip>
#include <stdio.h>
#include <cstring>
//#define test
using namespace std;
const int MAX_N = 8 + 2;
int vis[MAX_N];
int step[MAX_N];
int final_step[MAX_N];
int point[MAX_N][2];
int n;
double _min;
double disAll()
{
double sum = 0.0;
for(int i = 0;i < n - 1;i++)
sum += sqrt(pow(point[step[i]][0] - point[step[i+1]][0],2) + pow(point[step[i]][1] - point[step[i+1]][1],2));
sum += (n - 1 ) * 16;
return sum;
}
double disTwo(int i)
{
return sqrt(pow(point[final_step[i]][0] - point[final_step[i+1]][0],2) + pow(point[final_step[i]][1] - point[final_step[i+1]][1],2)) + 16;
}
void dfs(int cur)
{
if(cur == n)
{
double temp = disAll();
//_min = _min < temp ? _min : temp;
if(_min > temp)
{
_min = temp;
memcpy(final_step,step,sizeof(step));
}
}
else
{
for(int i = 0;i < n;i++)
{
if(vis[i])
continue;
step[cur] = i;
vis[i] = 1;
dfs(cur+1);
vis[i] = 0;
}
}
}
int main()
{
#ifdef test
freopen("in.txt","r",stdin);
#endif // test
int T = 1;
while(cin>>n,n)
{
_min = 1000000;
int i;
for(i = 0;i < n;i++)
cin>>point[i][0]>>point[i][1];
dfs(0);
cout<<"**********************************************************"<<endl;
cout<<"Network #"<<T++<<endl;
for(i = 0;i < n - 1;i++)
{
cout<<"Cable requirement to connect ("<<point[final_step[i]][0]<<","<<point[final_step[i]][1]<<") to ("<<point[final_step[i+1]][0]<<","<<point[final_step[i+1]][1]<<") is ";
cout<<fixed<<setprecision(2)<<disTwo(i);
cout<<" feet."<<endl;
}
cout<<"Number of feet of cable required is ";
cout<<fixed<<setprecision(2)<<_min;
cout<<"."<<endl;
}
return 0;
}