Pagini recente » Cod sursa (job #1162361) | Cod sursa (job #1890233) | Cod sursa (job #1137234) | Cod sursa (job #2230493) | Cod sursa (job #2139671)
#include<fstream>
#include<cmath>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int NMAX = 25e4 + 5, LOG2NMAX = 18;
int ancestor[LOG2NMAX][NMAX];
int nodesCount, queriesCount;
inline void readData(){
fin >> nodesCount >> queriesCount;
int i;
for(i = 1; i <= nodesCount; ++i)
fin >> ancestor[0][i];
}
inline void getAncestors(){
int i, j;
for(i = 1; (1 << i) <= nodesCount; ++i)
for(j = 1; j <= nodesCount; ++j)
ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];
}
inline int kthAncestor(int node, int k){
int lg = log2(k);
if((k & (k - 1)) == 0)
return ancestor[lg][node];
else
return kthAncestor(ancestor[lg][node], k - (1 << lg));
}
inline void solveQueries(){
int node, k;
while(queriesCount--){
fin >> node >> k;
fout << kthAncestor(node, k) << '\n';
}
}
int main(){
readData();
getAncestors();
solveQueries();
}