Advertisement
AlenAntonelli

Military Problem

Jul 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /// https://trello.com/c/ww0KRYeW/44-problem-e-codeforces
  2. /// http://codeforces.com/contest/1006/problem/E
  3.  
  4. #include <iostream>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. struct grafo {
  9.     vector< vector<int> > ady;
  10.     vector<int> sub;
  11.     vector<int> id;
  12.     vector<int> sec;
  13.     int n, q;
  14.    
  15.     void leer()
  16.     {
  17.         cin>>n>>q;
  18.        
  19.         ady.resize(n+1);
  20.         sub = vector<int> (n+1, 1);
  21.         id.resize(n+1);
  22.         sec.resize(n+1);
  23.        
  24.         int padre, hijo;
  25.         for (int i=2; i<=n; i++)
  26.         {
  27.             cin>>padre;
  28.             hijo = i;
  29.            
  30.             ady[padre].push_back(hijo);
  31.         }
  32.     }
  33.    
  34.     int pos = 1;
  35.     void DFS (int padre)
  36.     {
  37.         id[padre] = pos;
  38.         sec[pos] = padre;
  39.         pos++;
  40.        
  41.         for(int i=0; i<ady[padre].size(); i++)
  42.         {
  43.             int hijo = ady[padre][i];
  44.            
  45.             if ( sub[hijo] == 1 )
  46.                 DFS(hijo);
  47.            
  48.             sub[padre] += sub[hijo];
  49.         }
  50.     }
  51.    
  52.     void resultado ()
  53.     {
  54.         DFS(1);
  55.        
  56.         int u, k;
  57.         for (int i=0; i<q; i++)
  58.         {
  59.             cin>>u>>k;
  60.             if (k<= sub[u] )
  61.             {
  62.                 int ini = id[u];
  63.                 int fin = ini + k -1;
  64.                
  65.                 cout<<sec[fin]<<endl;
  66.             }
  67.             else cout<<"-1"<<endl;
  68.         }
  69.     }
  70.    
  71. };
  72.  
  73. int main()
  74. {
  75.     grafo g;
  76.     g.leer();
  77.     g.resultado();
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement