Cod sursa(job #51806)

Utilizator DastasIonescu Vlad Dastas Data 16 aprilie 2007 21:52:16
Problema Stramosi Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.17 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 == 1000 )
    {
        ThousandthAncestor[thousanc] = nr;
        depth -= 1001;
        thousanc = nr;
    }

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

    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;
}