CSES - Shared codeLink to this code:
https://cses.fi/paste/1270be4c9a98d13d96ba1a/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#define lli long long int
#define MOD 1000000007
#define endl '\n'
using namespace std;
void solve()
{
int n, q;
cin >> n >> q;
// vector<vector<int>> A(n, vector<int>(30));
int A[n][30];
for (int i = 0; i < n; i++)
{
int t;
cin >> t;
t--;
A[i][0] = t;
}
for (int j = 1; j < 30; j++)
{
for (int i = 0; i < n; i++)
{
A[i][j] = A[A[i][j - 1]][j - 1];
}
}
while (q--)
{
lli u, k;
cin >> u >> k;
u--;
lli ans = u;
int bit = 0;
while (k)
{
if (k & 1)
{
ans = A[ans][bit];
}
bit++;
k >>= 1;
}
cout << ans + 1 << endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// freopen("error.txt", "w", stderr);
int testCase = 1;
while (testCase--)
{
solve();
}
return 0;
}