Depth [search] eat cheese

Depth [search] eat cheese

topic

Title Description

Room stood n cheeses. A little mouse should eat them all, at least ask how much distance run? A mouse at the beginning of (0,0) point.

Input Format

Here Insert Picture Description## the output format
of a number, represents the minimum distance of the run, 2 decimal places.

Sample input and output

Input # 1 replication
. 4
1 1
1 -1
-1 1
-1 -1
output copy # 1
7.41

Description / Tips

1≤n≤15。

analysis

We started the search from the beginning, each time to go to different points, each time to finish than the previous minimum distance, take the minimum distance.

Note : Title is real, so the data is stored by double,
but also pruning, if you have not completed all of the points, it has been more than the current minimum distance, it would lose.

There are clearly other comments in the code. . . . . . .

Code

#include<iostream>
#include<cmath> 
#include<cstdio>
using namespace std;


int n;
double a[20],b[20];  //各存放每个点的x , y; 注意是实数 
bool vis[20];    //点是否被访问过 

double ans = 0x3f3f3f3f;

//sqrt( (x1-x2)^2  + (y1-y2)^2 )
double dis(int x,int y){
	sqrt((a[x]-a[y])*(a[x]-a[y]) + (b[x]-b[y])*(b[x]-b[y]) );
}

// dep 走了几个点,  f目前点位置,  s总的长度 
void dfs(int dep,int f,double s){
	//剪枝优化,如果当前的距离已经大于 目前走过的最短距离,那再走也没意义了 
	if(s > ans){
		return ;
	}
	//如果走到n个点, 取最小的距离 
	if(dep == n){
		ans = min(ans,s);
		return ;
	}
	
//从每个点开始dfs,	
	for(int i=1;i<=n;i++){
		if(!vis[i]){
			vis[i] = true;
			dfs(dep+1,i,s+dis(f,i));		//dep+1,走过的点数加1 
			vis[i] = false;					//i,这次走的位置, 
		}					//s+dis(f,i),上次的累加距离+目前位置f到下个位置i的距离 
	}	
}

int main(){
	
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i]>>b[i];
	}
	//起点位置(0,0),从起点开始搜 
	a[0]=b[0]=0;
	dfs(0,0,0);
	
	printf("%.2lf",ans);
	return 0;
}
Published 75 original articles · won praise 1 · views 3639

Guess you like

Origin blog.csdn.net/A793488316/article/details/104726380