Cod sursa(job #198143)

Utilizator andrei-alphaAndrei-Bogdan Antonescu andrei-alpha Data 8 iulie 2008 20:48:52
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.1 kb
#include <cstdio>
#include <vector>

#define IN "cerere.in"
#define OUT "cerere.out"
#define vv vector
#define N_MAX 100001
#define FOR(i,a,b) for(int i=a;i<=b;++i)

using namespace std;
vv <int> ks(N_MAX);
vv <int> stv(N_MAX);
vv <int> sol(N_MAX); 
int niv,N;

typedef struct nod  
{  
	int x;  
	nod *a;  
} *pNod;  
pNod v[N_MAX]; 

void scan()
{
	int x,y;
	pNod p;  
	freopen(IN, "r",stdin);
	freopen(OUT, "w",stdout);
	scanf("%d\n", &N);
	FOR(i,1,N)
		scanf("%d", &ks[i]);
	FOR(i,2,N)
	{
		scanf("%d %d\n",&x,&y);
		p = new nod;  
		p -> x = y;  
        p -> a = v[x];  
        v[x] = p;  
		stv[y] = 1;
	}	
}

void df(int nod)
{
	pNod p; 
	stv[++niv] = nod;
	
	if(!ks[nod])	
		sol[nod] = 0;
	else
		sol[nod] = sol[ stv[niv - ks[nod]]] + 1; 
	
	for (p = v[nod]; p != NULL; p = p -> a)  
		df(p->x); 
	--niv;	
}

void solve()
{
	int root;
	FOR(i,1,N)
		if(!stv[i])
			root = i,
			i=N+1;
	df(root);
}

void print()
{
	FOR(i,1,N-1)
		printf("%d ",sol[i]);
	printf("%d\n",sol[N]);
}

int main()
{
	scan();
	solve();
	print();
	return 0;
}