P1135 Strange Elevator

Topic description

Hehe, one day I had a dream about a very strange elevator. Each floor of the building can stop the elevator, and there is a number Ki​(0≤Ki​≤N) on the i-th floor (1≤i≤N). The elevator has only four buttons: on, off, up, down. The number of floors above and below is equal to the number on the current floor. Of course, if the requirements are not met, the corresponding button will fail. For example: 3, 3 ,1 ,2 ,5 represents Ki​(K1​=3,K2​=3,…), starting from the 11th floor. On the 1st floor, pressing "Up" can go to the 4th floor, but pressing "Down" does not work because there is no −2 floor. So, what is the minimum number of button presses required to get from building A to building B?

Input and output format

Input format:

 

A total of two lines.

The first line is three positive integers separated by spaces, representing N, A, B (1≤N≤200, 1≤A, B≤N).

The second line is N non-negative integers separated by spaces, representing Ki​.

 

Output format:

 

One line, that is, the minimum number of keystrokes, if it cannot be reached, output −1.

 

Input and output example

Input Example #1:  Copy

5 1 5
3 3 1 2 5

Output Sample #1:  Copy

3

 


At the beginning, the data can be passed, but the recursion will explode if the recursion is too deep, MLE (MEMORY LIMIT EXCEEDED)

#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int n,a,b; //n表示有几层楼,a、b是目标楼层 
int f[205];//记录每一层的k值 
int ans=inf;

void dfs(int now,int step) //now是现在所在的楼层  step是按键次数 
{
	if(now==b)
	{
		ans=min(ans,step);
		return;
	}
	if(now+f[now]<=n) //可以上升 
		dfs(now+f[now],step+1);
	if(now-f[now]>=1)//可以下降
		dfs(now-f[now],step+1);	
}
//这样写  爆栈了 ,最后MLE 
int main()
{
	ios::sync_with_stdio(false);
	cin>>n>>a>>b;
	for(int i=1;i<=n;i++)
		cin>>f[i];		
	dfs(a,0);
	cout<<ans<<endl;
	return 0;
}

 

It was later changed to:

#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int n,a,b; //n表示有几层楼,a、b是目标楼层 
int f[205];//记录每一层的k值 
int ans=inf;
int vis[205];

void dfs(int now,int step) //now是现在所在的楼层  step是按键次数 
{
	if(now==b)
	{
		ans=min(ans,step);
		return;
	}
	if(step<=ans) //这就是一个剪枝
	{
		vis[now]=1;
		if(now+f[now]<=n && !vis[now+f[now]]) //可以上升,还要注意判断一下是否访问过(也是一种剪枝) 
			dfs(now+f[now],step+1);
		if(now-f[now]>=1 && !vis[now-f[now]])//可以下降
			dfs(now-f[now],step+1);	
		vis[now]=0;	
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin>>n>>a>>b;
	for(int i=1;i<=n;i++)
		cin>>f[i];		
	dfs(a,0);
	if(ans!=inf)
		cout<<ans<<endl;
	else  //别忘了判断输出-1 
		cout<<-1<<endl;
	return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326389288&siteId=291194637