216UVA网络连线—回溯法

回溯法

中间无数低级错误

#include<stdio.h>
#include<string.h>
#include<math.h>
const int max = 10;
int x[max];
int y[max];
int vis[max];
int ans[max];
double minsum;
double dist(double x1,double x2,double y1,double y2)
{
	return pow((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2),0.5)+16;
}
void dfs(int cur,int n,double sum,int* now)
{
	if(sum >= minsum)
		return;
	if(cur==n)
	{
		if(sum < minsum)
		{
			minsum = sum;
			memcpy(ans,now,sizeof(ans));  // sizeof(now) is WRONG!!!
		}
		return;
	}
	//for(int i = 0; i<n&& !vis[i];i++) is WRONG!!!!!
	for(int i = 0; i<n;i++)
	{
		if(vis[i]) continue;
		now[cur]=i;          //记录点x[i],y[i]的编号i(now[cur])
		double dis = 0;
		if(cur)
			dis=dist(x[now[cur]],x[now[cur-1]],y[now[cur]],y[now[cur-1]]);
		vis[now[cur]] = 1;
		dfs(cur+1,n,sum+dis,now);
		vis[now[cur]] = 0;
	}
}
int main()
{
	//
	freopen("input.txt","r",stdin);
	int n;
	int numcs =1;
	while(scanf("%d",&n)==1 && n)
	{
		for(int i=0; i < n;i++)
		{
			scanf("%d%d",&x[i],&y[i]);
		}
		memset(vis,0,sizeof(vis));
		minsum = 2147483646;
		int now[10];
		dfs(0,n,0,now);
		puts("**********************************************************");
		printf("Network #%d\n",numcs++);
		for(int i = 0; i < n-1;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]],dist(x[ans[i]],x[ans[i+1]],y[ans[i]],y[ans[i+1]]));
		}
		printf("Number of feet of cable required is %.2f.\n",minsum);
	}
}
    原文作者:回溯法
    原文地址: https://blog.csdn.net/qq_33471057/article/details/55021756
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞