-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path1006E. Military Problem.cpp
58 lines (46 loc) · 993 Bytes
/
1006E. Military Problem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Idea:
- DFS Order.
- Using DFS we can construct the DFS order array and find
the size of each subtree.
- Using the information in the previous point we can solve each
query.
*/
#include <bits/stdc++.h>
using namespace std;
int const N = 2e5 + 1;
bool vis[N];
int n, q, idx[N], siz[N];
vector<int> ord;
vector<vector<int> > g;
int DFS(int u) {
vis[u] = true;
idx[u + 1] = ord.size();
ord.push_back(u + 1);
int ret = 1;
for(int i = 0; i < g[u].size(); ++i)
if(!vis[g[u][i]])
ret += DFS(g[u][i]);
return siz[u + 1] = ret;
}
int main() {
scanf("%d %d", &n, &q);
g.resize(n);
for(int i = 1, a; i < n; ++i) {
scanf("%d", &a);
--a;
g[a].push_back(i);
}
for(int i = 0; i < n; ++i)
sort(g[i].begin(), g[i].end());
DFS(0);
while(q-- != 0) {
int u, k;
scanf("%d %d", &u, &k);
if(idx[u] + siz[u] < idx[u] + k)
puts("-1");
else
printf("%d\n", ord[idx[u] + k - 1]);
}
return 0;
}