2 条题解

  • 0
    @ 2024-8-11 8:53:11

    dfs:

    #include <bits/stdc++.h>
    using namespace std;
    
    int N, A, B;
    int a[201], v[201], ans = INT_MAX, flag;
    int b[2] = {1, -1}; //电梯方向上1、下-1
    void dfs(int x, int cnt) {
        if(x == B) {
            ans = min(ans, cnt);
            flag = true;
            return;
        }
        for(int i=0; i<2; i++) {
            int nx = x + a[x]*b[i];
            if(nx < 1 || nx > B || v[nx]) continue;
            v[nx] = 1;
            dfs(nx, cnt+1);
            v[nx] = 0;
        }
    }
    
    int main() {
        cin>>N>>A>>B;
        for(int i=1; i<=N; i++) cin>>a[i];
        v[A] = 1;
        dfs(A, 0);
        if(flag) cout<<ans<<endl;
        else cout<<-1;
        return 0;
    }
    
    • 0
      @ 2024-8-11 8:52:46

      bfs:

      #include <bits/stdc++.h>
      using namespace std;
      
      int N, A, B;
      int a[201], v[201];
      struct Lift {
          int x; //第几层
          int cnt;//到达这一层按键次数
      };
      int bfs(){
          queue<Lift> q;
          q.push({A, 0});
          v[A] = true;
          while(!q.empty()) {
              Lift lift = q.front(); q.pop();
              if(lift.x == B) return lift.cnt;
              int up = lift.x + a[lift.x];//往上走
              if(up <= B && v[up] == 0) {
                  q.push({up, ++lift.cnt});
                  v[up] = true;
              }
              int down = lift.x - a[lift.x];//往下走
              if(down > 0 && v[down] == 0) {
                  q.push({down, ++lift.cnt});
                  v[down] = true;
              }
          }
          return -1;
      }
      
      int main() {
          cin>>N>>A>>B;
          for(int i=1; i<=N; i++) cin>>a[i];
          cout<<bfs();
          return 0;
      }
      
      
      • 1

      信息

      ID
      838
      时间
      1000ms
      内存
      256MiB
      难度
      10
      标签
      递交数
      6
      已通过
      3
      上传者