Cod sursa(job #1394344)

Utilizator mircea.dobreanuMircea Dobreanu mircea.dobreanu Data 20 martie 2015 11:27:25
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.64 kb
#include <fstream>
using namespace std;

ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int kMax = 250010;
const int kLog = 25;
int n, m, lg[kMax], TT[kMax][kLog];

int lsb(int x)
{
	return (x & -x);
}

int main()
{
	fin >> n >> m;
	for (int i = 1; i <= n; ++i)
		fin >> TT[i][0];

	for (int i = 1; i <= n; ++i)
		for (int j = 1; j < kLog; ++j)
			TT[i][j] = TT[TT[i][j - 1]][j - 1];

	for (int i = 2; i <= n; ++i)
		lg[i] = lg[i / 2] + 1; 

	while (m--)
	{
		int p, q;
		fin >> q >> p;
		
		int parent = q;	
		while (p)
		{
			int pwr2 = lsb(p);
			parent = TT[parent][lg[pwr2]];
			p -= pwr2;
		}
		fout << parent << '\n';
	}
	return 0;
}