fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5. #define nl '\n'
  6. #define ff first
  7. #define ss second
  8. #define pb push_back
  9. #define sik(x) {cout << x << nl; return;}
  10. const ll maxn = 2e5+20, mod = 1e9 + 7, inf = 1e10;
  11. typedef pair<ll,ll> pii;
  12.  
  13. ll n, q;
  14. vector<ll> g[maxn], ans;
  15. set<pii> qr[maxn];
  16. vector<ll> pth;
  17. bool vis[maxn];
  18.  
  19. void dfs(ll v) {
  20. vis[v] = 1;
  21. pth.pb(v);
  22. for (auto [k, i] : qr[v]) {
  23. if (pth.size() - k - 1 >= 0) ans[i] = pth[pth.size() - k - 1];
  24. else ans[i] = -1;
  25. }
  26. for (auto u : g[v]) {
  27. if (!vis[u]) dfs(u);
  28. }
  29. pth.pop_back();
  30. }
  31.  
  32. int32_t main() {
  33. //cout << fixed << setprecision(5);
  34. cin.tie(0)->sync_with_stdio(0);
  35. cin >> n >> q, ans.assign(q, {});
  36. for (int u = 2, v ; u <= n ; u ++) {
  37. cin >> v;
  38. g[u].pb(v);
  39. g[v].pb(u);
  40. }
  41. for (int i = 0 ; i < q ; i ++) {
  42. ll x, k; cin >> x >> k;
  43. qr[x].insert({k, i});
  44. }
  45. dfs(1);
  46.  
  47. for (auto i : ans) cout << i << nl;
  48. }
  49.  
Success #stdin #stdout 0.01s 17568KB
stdin
5 1
1 2 2 3
2 2
stdout
33