Pagini recente » Cod sursa (job #814283) | Cod sursa (job #960215) | Cod sursa (job #524986) | Cod sursa (job #1224504) | Cod sursa (job #2973343)
#include <fstream>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int DIM = 250010;
const int LOG = 20;
int n, m, x, k;
int father[DIM], ancestors[LOG][DIM];
void calculateAncestors() {
for (int node = 1; node <= n; node++)
ancestors[0][node] = father[node];
for (int pow = 1; pow < LOG; pow++)
for (int node = 1; node <= n; node++)
ancestors[pow][node] = ancestors[pow - 1][ancestors[pow - 1][node]];
}
int findAncestor(int node, int cnt) {
int ancestor = 0;
for (int pow = LOG - 1; pow >= 0 && cnt > 0; pow--) {
if (cnt >= (1 << pow)) {
ancestor = ancestors[pow][node];
node = ancestor;
cnt -= (1 << pow);
}
}
return ancestor;
}
int main() {
fin >> n >> m;
for (int i = 1; i <= n; i++)
fin >> father[i];
calculateAncestors();
for (int i = 1; i <= m; i++) {
fin >> x >> k;
fout << findAncestor(x, k) << '\n';
}
return 0;
}