其他分享
首页 > 其他分享> > A strange lift (BFS)

A strange lift (BFS)

作者:互联网

A strange lift
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35340 Accepted Submission(s): 12593

Problem Description

There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button “UP” , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button “DOWN” , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can’t go up high than N,and can’t go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button “UP”, and you’ll go up to the 4 th floor,and if you press the button “DOWN”, the lift can’t do it, because it can’t go down to the -2 th floor,as you know ,the -2 th floor isn’t exist.
Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button “UP” or “DOWN”?

Input

The input consists of several test cases.,Each test case contains two lines.
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,…kn.
A single 0 indicate the end of the input.

Output

For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can’t reach floor B,printf “-1”.

Sample Input

5 1 5
3 3 1 2 5
0

Sample Output

3

题目大意:在电梯上你只可以点两个键,一个是up键,一个是down键,顾名思义,up键只可以向上,但是向上到达的楼层只能是i - ki(i是第几层,ki是输入时对应第i层的数字);down键也是只能向下,且只能到达i - ki层,问从a层到b层最少要按多少次键。

BFS解答如下:(hdu通过的代码)

#include <iostream>
#include<queue>
using namespace std;
//int location[210];
int vis[210];//记录已经走过的楼层,未走过为0,走过为1
int step[210];//记录走到楼层的步数
int k[210];//输入的那n个数存在这里
int dir[] = { 1,-1,0 };//往三个方向走,向上、向下、在原地
int n, a, b;
void dfs()
{
	bool flag = true;
	queue<int>q;
	q.push(a);
	step[a] = 0;
	vis[a] = 1;
	while (!q.empty())
	{
		a = q.front();
		q.pop();
		if (a == b)
		{
			flag = false;
			printf("%d\n",step[b]);
		}
		for (int i = 0;i < 3;i++)
		{
			int t = a + dir[i] * k[a];
			if (t >= 1 && t <= n && !vis[t])
			{
				vis[t] = 1;
				step[t] = step[a] + 1;
				q.push(t);
			}
		}

	}
	if (flag)
		printf("-1\n");
}
int main()
{
	while (scanf_s("%d%d%d", &n, &a, &b) && n)
	{
		memset(vis, 0, sizeof(vis));
		memset(step, -1, sizeof(step));
		for (int i = 1;i <= n;i++)
			scanf_s("%d", &k[i]);
		dfs();
    }
	return 0;
}``

 

标签:210,floor,int,strange,BFS,step,lift,input
来源: https://blog.csdn.net/weixin_43697280/article/details/88255107