Pagini recente » Cod sursa (job #2139932) | Cod sursa (job #1838546) | Cod sursa (job #2003935) | Cod sursa (job #1151890) | Cod sursa (job #2752672)
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
int n, m, ancestors[50][250001];
void calculateAncestors()
{
for (int i = 1; pow(2, i) <= n; i++)
for (int j = 1; j <= n; j++)
ancestors[i][j] = ancestors[i-1][ancestors[i-1][j]];
}
int searchAncestor(int pos, int noAncestors)
{
int maxPow, ancestorP, index;
ancestorP = pos;
while (noAncestors != 0)
{
maxPow = 1;
index = 0;
while (maxPow * 2 <= noAncestors)
{
maxPow *= 2;
index++;
}
ancestorP = ancestors[index][ancestorP];
noAncestors -= maxPow;
}
return ancestorP;
}
int main()
{
int p, q;
fin>>n>>m;
for(int j = 1; j <= n; j++)
fin>>ancestors[0][j];
calculateAncestors();
for(int i = 1; i <= m; i++)
{
fin>>q>>p;
fout<<searchAncestor(q, p)<<"\n";
}
return 0;
}