A strange lift
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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
中文翻译:
问题描述
有一种奇怪的升降机。 电梯可以在每一层停车,每一层都有一个数字Ki(0 <= Ki <= N)。 电梯只有两个按钮:上下。 当你在第i层时,如果你按下“上”键,你就会到第i层。 e,你会走到i+Ki层,同样的,如果你按下按钮“DOWN”,你会走下Ki层,i。 e,你会到i-Ki - th层。 当然,升力上升的高度不能超过N,下降的高度也不能低于1。 例如,有一个5层的建筑物,k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5。 从1楼开始,你按下“上”键,就可以上到4楼,如果你按下“下”键,电梯就做不到,因为它下不了2楼,你知道,2楼是不存在的。
问题来了:当你在A层,你想去B层,他至少要按多少次“上”或“下”键?
输入
输入由几个测试用例组成。 ,每个测试用例包含两行。
第一行包含上面描述的三个整数N,A,B (1 <= N,A,B <= 200),第二行包含N个整数k1,k2,....kn。
单个0表示输入结束。
输出
对于输入输出一个整数的每一种情况,当你在a层,你想去B层时,你需要按下按钮的最少次数,如果你不能到达B层,就打印“-1”。
运用BFS广度优先搜索
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n,Start,End;//楼层数,开始点,终点
int a[202];
int vis[202];
struct pos{
int level;//当前状态
int steps;//走过的步数
};
void bfs();
int main()
{
int i;
while(~scanf("%d",&n))
{
if(n==0)
break;
scanf("%d%d",&Start,&End);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
vis[i]=0;
}
bfs();
}
return 0;
}
void bfs()
{
pos cur,nex;
cur.level=Start;
cur.steps=0;
queue<pos>qu;
qu.push(cur);
vis[Start]=1;
while(!qu.empty())
{
cur=qu.front();
qu.pop();
if(cur.level==End)
{
printf("%d\n",cur.steps);
return;
}
nex.level=cur.level+a[cur.level];
nex.steps=cur.steps+1;
if(nex.level<=n)
{
if(vis[nex.level]==0)
{
vis[nex.level]=1;
qu.push(nex);
}
}
nex.level=cur.level-a[cur.level];
nex.steps=cur.steps+1;
if(nex.level>=1)
{
if(vis[nex.level]==0)
{
vis[nex.level]=1;
qu.push(nex);
}
}
}
printf("-1\n");
return;
}