Advertisement
willy108

CSES 1687

Nov 12th, 2020
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cmath>
  4. #include <cstring>
  5. #include <cassert>
  6. #include <algorithm>
  7. #include <vector>
  8. #include <utility>
  9. #define max_v 220000
  10. #define SQRT 500
  11. #define cont continue
  12. using namespace std;
  13. int par[max_v], super[max_v]; //super stores the "super" parent or the parent SQRT layers up
  14. int n, q; //sqrt decomp for the win
  15. int main(){
  16.   scanf("%d%d", &n, &q);
  17.   for(int i = 2; i<=n; i++){
  18.     scanf("%d", &par[i]);
  19.   }
  20.  
  21.   for(int i = 1; i<=n; i++){
  22.     super[i] = i;
  23.     for(int j = 0; j<SQRT && super[i]; j++) super[i] = par[super[i]];
  24.   }
  25.  
  26.   while(q--){
  27.     int u, k;
  28.     scanf("%d%d", &u, &k);
  29.     for(; k >= SQRT; k -= SQRT){
  30.       u = super[u];
  31.     }
  32.     while(k--) u = par[u];
  33.     printf("%d\n", u ? u : -1);
  34.   }
  35.   return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement