Pagini recente » Cod sursa (job #2038618) | Cod sursa (job #1290716) | Cod sursa (job #2901481) | Cod sursa (job #898174) | Cod sursa (job #1043167)
#include <fstream>
#include <math.h>
using namespace std;
#define NMAX 250001
#define LOGNMAX 18
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
int ancestors[NMAX][LOGNMAX],m,n,p,q;
int main()
{
int i,j;
fin>>n>>m;
for(i=1;i<=n;i++)
fin>>ancestors[i][0];
int height = 1;
while(pow(2,height) < n)
{
for(int i=1;i<=n;i++)
ancestors[i][height]=ancestors[ancestors[i][height-1]][height-1];
height++;
}
while(m--)
{
fin>>q>>p;
while(p)
{
for(i=LOGNMAX+2;i>=0 && pow(2,i)>p;i--);
q = ancestors[q][i];
p -= pow(2,i);
}
fout<<q<<"\n";
}
return 0;
}