Cod sursa(job #51816)

Utilizator DastasIonescu Vlad Dastas Data 16 aprilie 2007 22:00:20
Problema Stramosi Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.18 kb
#include <stdio.h>
#include <iostream>

using namespace std;

int N[250000];

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

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

int ThousandthAncestor[250001];

int find(int nr, int times, int thousanc, int depth)
{
    if ( times == 0 ) return nr;
    if ( nr == 0 ) return 0;

    if ( depth == 6000 )
    {
        ThousandthAncestor[thousanc] = nr;
        depth -= 6001;
        thousanc = nr;
    }

    if ( times >= 6000 && ThousandthAncestor[nr] != 0 )
    {
        times -= 6000;
        nr = ThousandthAncestor[nr];
    }
    else
    {
        times -= 1;
        nr = N[nr-1];
    }

    return find(nr,times,thousanc,depth+1);
}


int main ()
{
	int temp1, temp2;

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

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

	for ( int i = m-1; i != -1; --i )
	{
	    fscanf(in, "%d %d", &temp1, &temp2);
	    fprintf(out, "%d\n", find(temp1, temp2, temp1, 0));
	}


	return 0;
}