题目描述:
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"?
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.
5 1 5 3 3 1 2 5 0
3
题目意思比较简单看看代码就能理解,只要注意到问题界限就可以了。
AC代码:
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int m,n,k;
int dr[2]={1,-1};//代表上下
int bj[205];
int s[205];
struct st
{
int x;//记录位置
int t;//记录次数
};
int bfs(int a)
{
int i,dx;
memset(bj,0,sizeof(bj));
queue<st> qu;
st now,ne;
now.x=a,now.t=0;
qu.push(now);
bj[a]=1;
while(!qu.empty())
{
now=qu.front();
qu.pop();
if(now.x==k)
return now.t;
else
{
for(i=0;i<2;i++)
{
dx=now.x+dr[i]*s[now.x];
if(dx>=1&&dx<=m)//判断是否在题目限制内
{
ne.x=dx;
ne.t=now.t;
if(dx==k)
return now.t+1;
if(bj[dx]==0)//判断是否是未搜索过的点
{
ne.t++;
qu.push(ne);
bj[dx]=1;
}
}
}
}
}
return -1;
}
int main()
{
int i,j,sum,a,b;
while(scanf("%d",&m)!=EOF,m)
{
scanf("%d%d",&n,&k);
for(i=1;i<=m;i++)
scanf("%d",&s[i]);
sum=bfs(n);
printf("%d\n",sum);
}
return 0;
}