Cod sursa(job #413474)

Utilizator RazvanSSavu Razvan RazvanS Data 8 martie 2010 17:21:08
Problema Stramosi Scor 80
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];

void dfs ( int nod , int * S, int depth ) {
	
		/* 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 */
		int child;
		
		while ( (child = pop (&Ad[nod] ) ) >= 0 ) {
			
				S [ ++depth ] = child;
				dfs ( child , S , depth );
				depth --;
		}
		
		/* Going up */		
		
}
		
int main ( void ) {
		
		/* Variables */ 
		int n, m, p, q, par, 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" , &par);
			push ( &Ad[par] , 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;
		
		while ( ( p = pop ( &Ad[0] ) ) > 0 )  {
			
				depth = 0;
				S[0] = p;
				dfs ( p , S ,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;
}