Cod sursa(job #1182016)

Utilizator tttesterLaura Surcel tttester Data 4 mai 2014 15:07:10
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <math.h>
/*#include <conio.h>
#include <sys\timeb.h> */

using namespace std;

long N, M;
long A[250001][18];

int main(int argc, char **argv)
{
	//struct timeb start, end;
	ifstream in("stramosi.in");
    std::ofstream out("stramosi.out");
    
    // read from infile.txt using cin
    cin.rdbuf(in.rdbuf());
	cout.rdbuf(out.rdbuf());
	
	//ftime(&start);
	
	// take input (I)
	cin>>N;
	
	for(int i = 1; i<=N; ++i)
		cin>>A[i][0];
	
	// process input
	int depth = log10(N) / log10(2);
	
	for(int i = 1; i<=N; ++i)
	{
		for(int j = 1; j<=depth; ++j)
		{
			long temp = A[i][j-1];
			A[i][j] = A[temp][j-1];
		}
	}
	
	// test print
	/*cout<<"Test print\n";
	for(int i = 0; i<=N; ++i)
	{
		for(int j = 0; j<=depth; ++j)
			cout << A[i][j] << " ";
		cout<<"\n";
	}*/
	
	// take input (II)
	cin>>M;
	
	for(int i = 1; i<=M; ++i)
	{
		long q, p;
		cin>>q>>p;
		/*cout<<"q= "<<q<<"\n";
		cout<<"p= "<<p<<"\n";*/
		
		long j = 0, r = q;
		while(p)
		{
			int digit = p & 1;
			if (digit)
				r = A[r][j];
			p >>= 1;
			++j;
		}
		
		/*cout<<"result= ";*/
		if(r == q)
			cout<<0<<"\n";
		else
			cout<<r<<"\n";
    }
    /*ftime(&end);
	
	cout<<"Time: \n"<<(1000.0 * (end.time - start.time)
        + (end.millitm - start.millitm))<<"\n";
	getch();*/
	return 0;
}