Cod sursa(job #481614)

Utilizator dcm9000Dinu Cristian Mircea - UPB dcm9000 Data 31 august 2010 23:09:18
Problema Stramosi Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.76 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>

using namespace std;

#define FILE_IN "stramosi.in"
#define FILE_OUT "stramosi.out"

int N, M;

int anc[250000][18];

int main()
{
	ifstream fisIn(FILE_IN);
    ofstream fisOut(FILE_OUT);

    fisIn >> N >> M;

    for (int i=0; i<N; i++) fisIn >> anc[i][0];

    for (int j=1; j<18; j++)
		for (int i=0; i<N; i++)
		{
			int temp = anc[i][j-1];
			anc[i][j] = temp ? anc[temp-1][j-1] : 0;
		}

	for (int i=0; i<M; i++)
	{
		int P,Q;
		
		fisIn >> Q >> P;

		int poz = Q;
		while (P && poz)
		{
			int bit = 31-__builtin_clz(P);
			if (bit > 17) { poz = 0; break; }
			
			P -= 1<<bit;
			poz = anc[poz-1][bit];
		}

		fisOut << poz << "\n";
	}
}