Cod sursa(job #413488)

Utilizator RazvanSSavu Razvan RazvanS Data 8 martie 2010 17:41:33
Problema Stramosi Scor 0
Compilator c Status done
Runda Arhiva de probleme Marime 2.06 kb
#include <stdio.h>
#include <stdlib.h>

#define file_in "stramosi.in"
#define file_out "stramosi.out"

#define N_MAX 250001
#define M_MAX 350001

struct list_elem {
	
		int nod;
		struct list_elem *next;
};

typedef struct list_elem list;

typedef list * stack;

stack new_stack ( void ) {
	
		list* l = (list*) calloc ( 1 , sizeof (list) );
		/* Final santinel condition */
		l -> next = 0;
		l -> nod = -1;
		
		return l;
}

int pop ( stack *S ) {
	
		if ( (*S) -> next == 0 ) return -1;
		
		int nr = (*S)->nod;
		stack aux = *S;
		*S = (*S)->next;
		free(aux);
		return nr;
}

void push ( stack *S , int elem ) {
	
		list* l = (list*) calloc ( 1 , sizeof (list) );
		
		l -> nod = elem;
		l -> next = *S ;
		*S = l;
}	

stack C[N_MAX] , Ad[N_MAX];
int P[N_MAX];


		
int main ( void ) {
		
		/* Variables */ 
		int n, m, p, q, i;
		

		
		/* Files */
		freopen ( file_in , "r", stdin);
		freopen ( file_out , "w", stdout);
		
		
		/* Read */
		scanf("%d%d" , &n, &m);
		
		for ( i=0 ; i<=n ; ++i ) 
			Ad[i] = new_stack ();
		
		for ( i=1 ; i<=n ; ++i ){
			
			scanf("%d" , &P[i]);
			push ( &Ad[P[i]] , i );
			
		}	
		
		// C[i] = stiva ce contine toate cererile de stramosi pentru i 
		for (i=1; i<=n ;++i) 
			C[i] = new_stack();
		int Ord[M_MAX], cont=0;
			
		for (i=1;i<=m;++i) {
			
				scanf("%d %d" , &q , &p );
				push(&C[q], p);
				Ord[++cont] = q;
		}
			
		int S[N_MAX], depth, nod, child;;
		
		while ( ( nod = pop ( &Ad[0] ) ) > 0 )  {
			
			S[0] = nod;
			depth = 0;			
				/* DFS */
				
			while ( nod > 0 ) {
				
			/* Prelucrare */
		
			int par, val;
			stack st = new_stack ();
			while ( (par = pop (&C[nod])) >= 0 ) {
			
				val = par > depth ? 0 : S[depth - par];
				
				push ( &st , val );
				
			}
		
			free ( C[nod] );
			C[nod] = st;
		
			/* Deep it */
			
		
			child = pop (&Ad[nod] );
			if ( child > 0 ) {
			
				S [ ++depth ] = child;
				nod = child;
			}
			else {
				nod = P[nod];
				depth --;
			}
		 }
	}
		
		/* Print Sol in the order of Ord */
		
		for (i=1;i<=m;++i) {
			
				q = Ord [i];
				printf("%d\n", pop ( &C[q] ) );
		}
		 
		
		return 0;
}