Pagini recente » Cod sursa (job #2190395) | Cod sursa (job #1316868) | Cod sursa (job #962228) | Cod sursa (job #378432) | Cod sursa (job #2305763)
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define MOD 666013
using namespace std;
typedef long long ll;
typedef pair< int , int > PII;
int n, m, a[250100][20];
vector < int > V[250100];
bitset < 250100 > B;
void dfs(int x) {
B[x] = 1;
for (int i = 1; i <= 18; i++) {
a[x][i] = a[a[x][i - 1]][i - 1];
}
for (auto it : V[x]) {
if (B[it]) continue;
dfs(it);
}
}
int main(){
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i][0];
V[a[i][0]].push_back(i);
}
for (int i = 1; i <= n; i++) {
if (a[i][0] == 0) dfs(i);
}
while (m--) {
int x, y;
cin >> x >> y;
while (y) {
int lg = log2(y);
x = a[x][lg];
y -= (1 << lg);
}
cout << x << "\n";
}
return 0;
}