Cod sursa(job #683306)

Utilizator eukristianCristian L. eukristian Data 20 februarie 2012 14:03:59
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.21 kb
#include <cstdio>
#include <cstdlib>
#define MAXN 100002

struct node {
	int key;
	node *next;
};

node *gr[MAXN];
int N, kval[MAXN], stack[MAXN], parent[MAXN], answer[MAXN], stackLevel;
char color[MAXN];

inline void add(int a, int b)
{
	node *q = (node *) malloc(sizeof(node));
	q->key = a;
	q->next = gr[b];
	gr[b] = q;
	
	q = (node *) malloc(sizeof(node));
	q->key = b;
	q->next = gr[a];
	gr[a] = q;
}

int read();
void dfs(int root);

int main()
{
	int root = read();
	dfs(root);
	
	freopen("cerere.out", "w", stdout);
	for (int i = 1 ; i < N ; ++i)
		printf("%d ", answer[i]);
	printf("%d\n", answer[N]);	
	
	return 0;
}

int read()
{
	freopen("cerere.in", "r", stdin);
	scanf("%d", &N);
	
	for (int i = 1 ; i <= N ; ++i)
		scanf("%d", &kval[i]);
	
	for (int i = 1 ; i < N ; ++i)
	{
		int a, b;
		scanf("%d%d", &a, &b);
		add(a, b);
		
		parent[b] = a;
	}
	
	int root = 1;
	while (parent[root] != 0)
		root = parent[root];
		
	return root;
}

void dfs(int root)
{
	stack[++stackLevel] = root;
	color[root] = 1;
	if (kval[root] != 0)
		answer[root] = answer[stack[stackLevel - kval[root]]] + 1;
	
	node *q = gr[root];
	while (q)
	{
		if (color[q->key] == 0)
			dfs(q->key);
		q = q->next;
	}
	
	//color[root] = 2;
	stackLevel--;
}