Pagini recente » Istoria paginii runda/tema123 | Atasamentele paginii Clasament oji200424234 | Cod sursa (job #1662805) | Cod sursa (job #440063) | Cod sursa (job #1713533)
#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() {
queue<int> Q;
Q.push(0);
while(!Q.empty()) {
int node = Q.front();
Q.pop();
for(int vec : G[node]) {
Depth[vec] = Depth[node] + 1;
Parent[vec] = node;
Link[vec] = (Depth[node] % kSqrt) ? Link[node] : node;
Q.push(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();
while(m--) {
int a, b;
cin >> a >> b;
cout << kth(a, b) << '\n';
}
return 0;
}