Cod sursa(job #175246)

Utilizator alex_mircescuAlex Mircescu alex_mircescu Data 9 aprilie 2008 19:11:13
Problema Asmax Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.92 kb
#include <stdio.h>
#include <math.h>

#define maxn 16*1024

long i, a, b, n, sel[maxn], v[maxn * 2], max = 0, next[maxn*2], first[maxn], val[maxn];

long depthsearch(long a) {
	long x, p, s = 0;
	sel[a] = 1;
	x = first[a];
	
	while(x > 0) {
		if (sel[v[x]] == 0) { 
			p = depthsearch(v[x]);
			s += p;
		}
		x = next[x];
	}
	if (s + val[a] > max) {
		max = s + val[a];
	}
	if (s + val[a] < 0) {
		return 0;
	}
	return s + val[a];
}


int main() {
	freopen("asmax.in","r",stdin);
	freopen("asmax.out","w",stdout);
	
	scanf("%ld", &n);
	for (i = 1;i <= n; ++i) {
		scanf("%ld", &val[i]);
		if (val[i] > max) {
			max = val[i];
		}
	}
	
	for (i = 1;i < n; ++i) {
		scanf("%ld %ld", &a, &b);
		v[i * 2 - 1] = a;
		v[i * 2] = b;
		next[i * 2] = first[a]; 
		first[a] = i * 2;
		next[i * 2 - 1] = first[b]; 
		first[b] = i * 2 - 1;
	}
	depthsearch(1);
	printf("%ld\n", max);
	return 0;
}