-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path1750 PlanetQueries1.cpp
80 lines (58 loc) · 1.23 KB
/
1750 PlanetQueries1.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// JAI BAJARANG BALI
// manitianajay45
// give me some sunshine, give me some rain, give me another chance to grow up once again....
// sab moh maya hai....
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
vector<ll> graph[200005];
vector<ll> ans(200005,0);
vector<bool> visited(200005,false);
ll dp[200005][31];
ll n,q;
void binlift(){
for(ll i=1;i<31;i++){
for(ll j=1;j<=n;j++){
dp[j][i]=dp[dp[j][i-1]][i-1];
}
}
}
ll query(ll x,ll k){
ll prev=x;
for(ll i=31;i>=0;i--){
if((k>>i)&1){
// cout<<i<<"i"<<endl;
prev=dp[prev][i];
}
}
return prev;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin>>n>>q;
ll arr[n+1];
memset(dp,-1,sizeof(dp));
for(ll i=1;i<=n;i++){
cin>>arr[i];
dp[i][0]=arr[i];
}
// for(ll i=1;i<=n;i++)
// {
// for(ll j=0;j<=3;j++){
// cout<<dp[i][j]<<" ";
// }
// cout<<endl;
// }
// cout<<"YES"<<endl;
binlift();
while(q--){
ll x,k;
cin>>x>>k;
ll ans=query(x,k);
cout<<ans<<endl;
}
return 0;
}