P1135 Strange elevator【BFS】

https://www.luogu.com.cn/problem/P1135

Title description

Haha, one day I had a dream, and I dreamed of a very strange elevator. Each floor of the building can stop the elevator, and the ii floor (1 \le i \le N)(1≤i≤N) has a number K_i(0 \le K_i \le N)Ki​(0 ≤Ki​≤N). The elevator has only four buttons: open, close, up and 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 buttons will fail. For example: 3, 3 ,1 ,2,53,3,1,2,5 represents K_i(K_1=3,K_2=3,...)Ki​(K1​=3,K2​=3,...), from Start on the 11th floor. On the 11th floor, press "up" to reach the 44th floor, and press "down" will not work, because there is no -2-2 floor. So, how many times do you need to press the button from the AA building to the BB building at least?

Input format

There are two lines.

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

The second line is NN non-negative integers separated by spaces, representing K_iKi​.

Output format

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

Sample input and output

Enter #1 to copy

5 1 5
3 3 1 2 5

Output #1 copy

3

Solution: The general BFS writing method is to determine whether the current position is legal to go up and down. If it is legal, put it in the queue, and the mark has passed. Illegal will not be processed.

At the beginning, I forgot the initialization and vis mark, and I had marked it in my consciousness. I forgot to write it, and I stuck for a long time.

#include <stdio.h>
#include <string.h>
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;

struct node
{
    int x,step;
} w,l;
bool vis[210];
int a[205];
void bfs(int s, int e,int n)
{
    memset(vis,0,sizeof(vis));
    vis[s] = 1;
    w.x = s;
    w.step = 0;
    queue<node>q;
    q.push(w);
    int flag = 0;
    while(!q.empty()){
        w = q.front();
        q.pop();
        if(w.x == e){
            flag = 1;
            printf("%d\n",w.step);
            return ;
        }
        int tu = w.x + a[w.x];
        int td = w.x - a[w.x];
//        cout << tu << " " << td <<endl;
        if(tu <= n && vis[tu] == 0){
            l.x = tu;
            l.step = w.step + 1;
            vis[tu] = 1;
            q.push(l);
        }
        if(td >= 1 && vis[td] == 0){
            l.x = td;
            l.step = w.step + 1;
            vis[td] == 1;
            q.push(l);
        }
    }
    if(flag == 0){
        printf("-1\n");
    }
    return ;
}
int main()
{
   int n,s,e;
//   cin >> n >> s >> e;
    scanf("%d%d%d",&n,&s,&e);
   for(int i = 1; i <= n; i ++){
        scanf("%d",&a[i]);
   }
   if(s == e) printf("0\n");
   else
        bfs(s,e,n);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/Mercury_Lc/article/details/108903146