Link to this code: https://cses.fi/paste/7d2b7a0b66df52a2ea28b6/
#include <bits/stdc++.h>
#pragma GCC optimize("O3,unroll-loops")
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;
#define fori(N) for(ll i = 0; i < N; i++)
std::mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());
const ll m1 = 1e9+7;
const ll m2 = 998244353;

template<typename T>
using ordered_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;

template<typename Iterable>
void display(Iterable& arr) 
{
    for (auto i : arr) 
    {
        cout << i << " ";
    }
    cout << endl;
}

void solve()
{  
    int n, q;
    cin >> n >> q;
    vector<vector<int>> node(n+1, vector<int>(31));
    fori(n) cin >> node[i+1][0];
    for(int k = 1; k <= 30; k++)
    {
        for(int i = 1; i <= n; i++)
        {
            node[i][k] = node[node[i][k-1]][k-1];
        }
    } 
    while(q--)
    {
        int start, dist;
        cin >> start >> dist;
        // if (dist == 0)
        // {
        //     cout << start << '\n';
        //     continue;
        // }
        int ans = start;
        for(int i = 0; i <= 30; i++) if ((dist & (1 << i))) ans = node[ans][i];
        cout << ans << '\n';
    }
}   
 

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll n = 1;
    // cin >> n;
    auto begin = std::chrono::high_resolution_clock::now();
    while(n--) solve();
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    //cerr << "Execution Time: " << elapsed.count()*1e-6 << " milliseconds\n";
    return 0;
}