Cod sursa(job #53503)

Utilizator chermanCorina Herman cherman Data 22 aprilie 2007 13:12:17
Problema Stramosi Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.8 kb
#include <stdio.h>
#include <iostream>
#include <math.h>

using namespace std;

int N[250000];
int a[250000][18];

FILE *in = fopen("stramosi.in", "r"), *out = fopen("stramosi.out", "w");
int n, m;

inline int findtest(int nr, int times)
{
    cout << nr<<" " <<times<<endl;
    int x =log2(times);
    while ( a[nr][x] == -1 )
        --x;


    if ( x == log2(times) )
    {
        return a[nr][x];
    }

    cout << "x="<<x<<endl;

    cout << times-x<<" "<<times<<endl;

    int nn=nr;
    nr = a[nr][x];
    cout << "nr="<<nr<<endl;
	for ( int i = times-x; i <= times; ++i )
	{
        cout << "nr="<<nr<<endl;
		if ( a[nr][times-1] == 0 )
			return 0;
		nr = a[nr][i-1];
        //a[(int)log2(nn)][x] = nr;
	}

  return nr;
}

inline int findvlad(int nr, int times)
{
    nr = N[nr-1];
    //cout<<nr<<endl;
	for ( int i = times-1; i != 0; i-- )
	{
		if ( N[nr-1] == 0 )
			return 0;
		nr = N[nr-1];
	}

  return nr;
}

inline int findcorina(int nr, int times)
{
    int col=log2(times);
    nr = N[nr-1];

    while (a[nr-1][col]==-1) col--;

 	for ( int i = pow(2,col)+1;i<= times; i++ )
	{
		if ( (int)log2(i)==pow(2,i))
		{
		    if (a[nr-1][(int)log2(i)]==0) return 0;
		    else a[nr-1][(int)log2(i)]=nr;
		}
		nr = N[nr-1];
	}

  return nr;
}

int main ()
{
	int temp1, temp2;

	fscanf(in, "%d %d", &n, &m);

	for ( int i = 0; i != n; ++i )
	{
		fscanf(in, "%d", &N[i]);
		a[i][0] = N[i];
		for ( int j = 1; j != 18; ++j )
            a[i][j] = -1;
	}



	for ( int i = m-1; i != -1; --i )
	{

	    fscanf(in, "%d %d", &temp1, &temp2);
	    //fprintf(out, "%d\n", findvlad(temp1, temp2));
	    //fprintf(stdout, "%d\n", find1(temp1-1, temp2));
	    fprintf(out, "%d\n", findcorina(temp1, temp2));
     }



	return 0;
}