-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompanyQueriesI.cpp
More file actions
70 lines (59 loc) · 1.07 KB
/
Copy pathCompanyQueriesI.cpp
File metadata and controls
70 lines (59 loc) · 1.07 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
int n, q;
const int Sz = 2e5 + 2;
int par[Sz + 1];
vector <int> adj[Sz + 1];
int lv[Sz + 1];
void dfs(int u, int p){
int v;
for(int i = 0; i < (int)adj[u].size(); i++){
v = adj[u][i];
if(v != p){
lv[v] = lv[u] + 1;
dfs(v, u);
}
}
}
int dp[Sz + 1][19];
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> q;
for(int i = 2; i <= n; i++){
cin >> par[i];
adj[i].push_back(par[i]);
adj[par[i]].push_back(i);
}
lv[1] = 1;
dfs(1, 1);
for(int i = 1; i <= n; i++) dp[i][0] = par[i];
for(int j = 1; (1 << j) <= n; j++){
for(int i = 1; i <= n; i++){
if(lv[i] - (1 << j) >= 1){
dp[i][j] = dp[dp[i][j - 1]][j - 1];
}
}
}
/*
for(int i = 1; i <= n; i++){
for(int j = 0; j <= 2; j++) cout << dp[i][j] << ' ';
cout << "\n";
}
return 0;
*/
int x, k;
while(q--){
cin >> x >> k;
if(lv[x] - k < 1){
cout << "-1\n";
continue;
}
for(int i = 17; i >= 0; i--){
if(k < (1 << i)) continue;
k -= (1 << i);
x = dp[x][i];
}
cout << x << "\n";
}
}