Advertisement
Josif_tepe

Untitled

Oct 29th, 2023
935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <fstream>
  5. using namespace std;
  6. const int maxn = 1e5 + 10;
  7. int n, m;
  8. vector<int> graph[maxn];
  9.  
  10. int main() {
  11.     cin >> n >> m;
  12.     vector<int> parent(n + 1, -1);
  13.     for(int i = 2; i <= n; i++) {
  14.         int x;
  15.         cin >> x;
  16.         parent[i] = x;
  17.     }
  18.     for(int i = 0; i < m; i++) {
  19.         int x, k;
  20.         cin >> x >> k;
  21.         int ancestor = x;
  22.         for(int j = 0; j < k; j++) {
  23.             ancestor = parent[ancestor];
  24.             if(ancestor == -1) {
  25.                 break;
  26.             }
  27.         }
  28.         cout << ancestor << endl;
  29.     }
  30.     return 0;
  31. }
  32.  
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement