-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryLifting.cpp
More file actions
64 lines (52 loc) · 899 Bytes
/
binaryLifting.cpp
File metadata and controls
64 lines (52 loc) · 899 Bytes
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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<vector<int>>dp(200001,vector<int>(20));
void precompute(){
int k = ceil(log2(x));
for(int j=1;j<=k;j++){
for(int i=0;i<x;i++){
int par=dp[i][j-1];
if(par!=-1){
dp[i][j]=dp[par][j-1];/
}
}
}
}
void dfs(vector<vector<int>> &graph, int sou, int par, int level, vector<int>&depth){
dp[sou][0]=par;
depth[sou]=level;
for(auto it:graph[sou]){
if(it!=par){
dfs(graph,it,sou,level+1,depth);
}
}
}
int main(){
int x,y;
cin>>x>>y;
vector<int>v(x);
for(int i=0;i<x-1;i++){
cin>>v[i];
}
vector<vector<int>>graph(x);
for(int i=0;i<x-1;i++){
graph[v[i]-1].push_back(i+1);
graph[i+1].push_back(v[i]-1);
}
while(y--){
int a, b;
cin>>a>>b;
a--;
if(depth[a]<b){
cout<<-1<<endl;
continue;
}
while(b>0){
int c = log2(b);
b=dp[b][c];
b-=1<<c;
}
}
return 0;
}