Advertisement
tepyotin2

Up and Down

May 1st, 2025
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     while (true) {
  10.         int N, A, B;
  11.         cin >> N;
  12.         if (N == 0) break;
  13.  
  14.         cin >> A >> B;
  15.  
  16.         vector<int> K(N + 1);  // Floor indices from 1 to N
  17.         for (int i = 1; i <= N; ++i) {
  18.             cin >> K[i];
  19.         }
  20.  
  21.         vector<int> visited(N + 1, -1);  // visited[i] = number of presses to reach floor i
  22.         queue<int> q;
  23.  
  24.         q.push(A);
  25.         visited[A] = 0;
  26.  
  27.         while (!q.empty()) {
  28.             int current = q.front();
  29.             q.pop();
  30.  
  31.             if (current == B) break;
  32.  
  33.             int up = current + K[current];
  34.             int down = current - K[current];
  35.  
  36.             if (up <= N && visited[up] == -1) {
  37.                 visited[up] = visited[current] + 1;
  38.                 q.push(up);
  39.             }
  40.  
  41.             if (down >= 1 && visited[down] == -1) {
  42.                 visited[down] = visited[current] + 1;
  43.                 q.push(down);
  44.             }
  45.         }
  46.  
  47.         cout << visited[B] << endl;
  48.     }
  49.  
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement