B - A strange lif

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

题意概括  :

一个电梯能够上下移动,每一层都有一个数字,给你起点和终点,在当前层要想继续移动只能够根据每层的编号进行加多少层或减多少层,移动不能超过电梯所给层数的范围,问如果能够到达则输出最短移动次数,不能输出-1.

解题思路  :

深搜,直接从起点开始搜索,分两种情况,找到所有的情况,每次更新最短路径.

 

#include<stdio.h>
#include<string.h>

#define INT_MAX 2147483647
int book[201],a[201],min;
int n,b,c;

void dfs(int x,int step)
{
    if(x < 1||x > n)
    return;
    if(x == c)
    {
        if(step < min)
        {
            min = step;
        }
        return;
    }
    if(step>=book[x])
    return;
    book[x] = step;
    dfs(x+a[x],step+1);
    dfs(x-a[x],step+1);
}
int main()
{
    int i,k,step;
    while(~ scanf("%d",&n))
    {
        if(n == 0)
        break;
        step = 0;
        min = INT_MAX;
        scanf("%d%d",&b,&c);
        for(i = 1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            book[i] = INT_MAX-10;
        }
        dfs(b,step);
        if(min == INT_MAX)
        printf("-1\n");
        else
        printf("%d\n",min);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/y1356998843/article/details/81094309
今日推荐