Pagini recente » Cod sursa (job #1218736) | Cod sursa (job #1199123) | Istoria paginii runda/mehedinti01/clasament | Cod sursa (job #2711376) | Cod sursa (job #1713532)
#include <bits/stdc++.h>
using namespace std;
const int kMaxN = 250005;
const int kSqrt = 333;
int Depth[kMaxN], Parent[kMaxN], Link[kMaxN];
vector<int> G[kMaxN];
void dfs(int node) {
for(auto vec : G[node]) {
Depth[vec] = Depth[node] + 1;
Parent[vec] = node;
if(Depth[vec] % kSqrt)
Link[vec] = Link[node];
else
Link[vec] = node;
dfs(vec);
}
}
int kth(int node, int k) {
int seek_d = Depth[node] - k;
if(seek_d <= 0) return 0;
while(Depth[Link[node]] > seek_d)
node = Link[node];
while(Depth[node] != seek_d)
node = Parent[node];
return node;
}
int main() {
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
int n, m, p;
cin >> n >> m;
for(int i = 1; i <= n; ++i) {
cin >> p;
G[p].push_back(i);
}
dfs(0);
while(m--) {
int a, b;
cin >> a >> b;
cout << kth(a, b) << '\n';
}
return 0;
}