fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int dfs(std::vector<bool>& vis, int ci, vector<int>& v, vector<vector<int>>& list,unordered_map<int,int> & lenc){
  4. vis.at(ci)=1;
  5. v.push_back(ci);
  6. int uji=-1;
  7. int l=-1;
  8. for(int i=0;i<(int)list.at(ci).size();i++){
  9. if(vis.at(list.at(ci).at(i))==0){
  10. l=1;
  11. uji= dfs(vis,list.at(ci).at(i),v,list,lenc);
  12. }
  13. }
  14. if(l==-1) {lenc.at(ci)=ci; return ci;}
  15. lenc.at(ci)=uji;
  16. return uji;
  17. }
  18. int main() {
  19. int n,q;
  20. scanf("%d%d",&n,&q);
  21. vector<vector<int>> list(n+1);
  22. for(int i=2;i<=n;i++){
  23. int a;
  24. scanf("%d",&a);
  25. list.at(a).push_back(i);
  26. list.at(i).push_back(a);
  27. }
  28. for(int i=1;i<=n;i++){
  29. sort(list.at(i).begin(),list.at(i).end());
  30. }
  31. unordered_map<int,int> lenc;
  32. vector<int> v;
  33. std::vector<bool> vis(1+n, false);
  34. dfs(vis,1,v,list,lenc);
  35. unordered_map<int,int> m;
  36.  
  37. for(int i=0;i<(int)v.size();i++){
  38. m[v[i]]=i;
  39. }
  40.  
  41. while(q--){
  42. int a,b;
  43. cin>>a>>b;
  44. int i1=m.at(a);
  45. int i2=m.at(lenc.at(a));
  46. if(i1+b-1>i2) printf("-1\n");
  47. else printf("%d\n",v.at(i1+b-1));
  48. }
  49. }
Runtime error #stdin #stdout #stderr 0s 4392KB
stdin
9 6
1 1 1 3 5 3 5 7
3 1
1 5
3 4
7 3
1 8
1 9
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::out_of_range'
  what():  _Map_base::at