P1122 最大子树和https://www.luogu.com.cn/problem/P1122
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <unordered_map>
#include <cmath>
#include <map>
#include <cctype>
#include <cstdlib>
#include <deque>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int n;
int f[MAXN];
int head[MAXN];
int nxt[MAXN];
int ver[MAXN];
int cnt;
int ans = -INF;
inline void add(int x, int y) {
ver[++cnt] = y;
nxt[cnt] = head[x];
head[x] = cnt;
}
void dp(int p, int fa) {
for (int i = head[p]; i; i = nxt[i]) {
int v = ver[i];
if (v == fa)
continue;
dp(v, p);
f[p] += f[v] > 0 ? f[v] : 0;
}
ans = max(f[p], ans);
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", f + i);
ans = max(ans, f[i]);
}
int x, y;
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
add(x, y);
add(y, x);
}
dp(1, 0);
printf("%d", ans);
return 0;
}