Pagini recente » Cod sursa (job #1786269) | Cod sursa (job #1782908) | Cod sursa (job #783131) | Cod sursa (job #2095762) | Cod sursa (job #3212441)
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <vector>
const int32_t MAX_N = 250000;
const int32_t MAX_N_LOG_2 = 17;
int32_t ances[MAX_N][MAX_N_LOG_2];
int main() {
std::ifstream fin("stramosi.in");
std::ofstream fout("stramosi.out");
int32_t n, m;
fin >> n >> m;
for(int32_t i = 0; i != n; ++i) {
int32_t prev;
fin >> prev;
--prev;
ances[i][0] = prev;
}
for(int32_t i = 1; i != MAX_N_LOG_2; ++i) {
for(int32_t j = 0; j != n; ++j) {
int32_t prevAnces = ances[j][i - 1];
if(prevAnces == -1) {
ances[j][i] = -1;
} else {
ances[j][i] = ances[ances[j][i - 1]][i - 1];
}
}
}
for(int32_t i = 0; i != m; ++i) {
int32_t q, p;
fin >> q >> p;
--q;
for(int32_t j = 0; p && q != -1; ++j, p >>= 1) {
if(p & 1)
q = ances[q][j];
}
fout << (q + 1) << '\n';
}
fin.close();
fout.close();
return 0;
}