
倍增法
#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
#define f first
#define s second
#define fastio ios_base::sync_with_stdio(0);cin.tie(0)
using namespace std;
//declare
const int maxn = 2e5+5;
int n,q,nxt[maxn],jump[maxn][32 + 1];
vector<int> ans;
//
void build(){
for(int j=1;j<=32;j++){
for(int i=1;i<=n;i++){
jump[i][j] = jump[jump[i][j-1]][j-1];
}
}
}
int query(int a,int b){
for(int i=0;i<=32;i++){
if((1ll << i) & b){
a = jump[a][i];
}
}
return a;
}
signed main(){
fastio;
cin>>n>>q;
for(int i=1;i<=n;i++) cin>>jump[i][0];
build();
while(q--){
int a,b; cin>>a>>b;
cout<<query(a,b)<<"\n";
}
return 0;
}

發表留言