UVA_216
这个题目可以直接深搜,深搜的边界就是加入line的点为n,当总长度比标记过的长度小的时候,即可更新记录line的数组和总长度。
#include<stdio.h>
#include<string.h>
#include<math.h>
int n,x[10],y[10],vis[10];
int temp[10],ans[10];
double total;
void dfs(int cur,double t)
{
int i;
double k,t_x,t_y;
if(cur==n)
{
if(t<total)
{
total=t;
memcpy(ans,temp,sizeof(temp));
}
return;
}
for(i=0;i<n;i++)
if(!vis[i])
{
vis[i]=1;
temp[cur]=i;
t_x=x[temp[cur]]-x[temp[cur-1]];
t_y=y[temp[cur]]-y[temp[cur-1]];
dfs(cur+1,t+sqrt(t_x*t_x+t_y*t_y));
vis[i]=0;
}
}
int main()
{
int i,j,k,t,t_x,t_y;
t=0;
while(1)
{
scanf("%d",&n);
if(n==0)
break;
for(i=0;i<n;i++)
scanf("%d%d",&x[i],&y[i]);
memset(vis,0,sizeof(vis));
total=1000000000.0;
for(i=0;i<n;i++)
{
vis[i]=1;
temp[0]=i;
dfs(1,0.0);
vis[i]=0;
}
printf("**********************************************************\n");
printf("Network #%d\n",++t);
for(i=0;i<n-1;i++)
{
t_x=x[ans[i+1]]-x[ans[i]];
t_y=y[ans[i+1]]-y[ans[i]];
printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2f feet.\n",
x[ans[i]],y[ans[i]],x[ans[i+1]],y[ans[i+1]],16+sqrt(t_x*t_x+t_y*t_y));
}
printf("Number of feet of cable required is %.2f.\n",total+16*(n-1));
}
return 0;
}