Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// https://trello.com/c/ww0KRYeW/44-problem-e-codeforces
- /// http://codeforces.com/contest/1006/problem/E
- #include <iostream>
- #include <vector>
- using namespace std;
- struct grafo {
- vector< vector<int> > ady;
- vector<int> sub;
- vector<int> id;
- vector<int> sec;
- int n, q;
- void leer()
- {
- cin>>n>>q;
- ady.resize(n+1);
- sub = vector<int> (n+1, 1);
- id.resize(n+1);
- sec.resize(n+1);
- int padre, hijo;
- for (int i=2; i<=n; i++)
- {
- cin>>padre;
- hijo = i;
- ady[padre].push_back(hijo);
- }
- }
- int pos = 1;
- void DFS (int padre)
- {
- id[padre] = pos;
- sec[pos] = padre;
- pos++;
- for(int i=0; i<ady[padre].size(); i++)
- {
- int hijo = ady[padre][i];
- if ( sub[hijo] == 1 )
- DFS(hijo);
- sub[padre] += sub[hijo];
- }
- }
- void resultado ()
- {
- DFS(1);
- int u, k;
- for (int i=0; i<q; i++)
- {
- cin>>u>>k;
- if (k<= sub[u] )
- {
- int ini = id[u];
- int fin = ini + k -1;
- cout<<sec[fin]<<endl;
- }
- else cout<<"-1"<<endl;
- }
- }
- };
- int main()
- {
- grafo g;
- g.leer();
- g.resultado();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement