思路
dp[i]表示以i为根的树的最大值,对于一棵子树要么选,要么不选。最终求个最大值即可。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+5;
const int INF = 0x3f3f3f3f;
int n, w[MAXN], dp[MAXN];
vector<int> G[MAXN];
int dfs(int u, int fa)
{
dp[u] = w[u];
for (auto v: G[u])
{
if (v != fa)
dp[u] += max(0, dfs(v, u));
}
return dp[u];
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
for (int i = 1; i < n; i++)
{
int u, v; scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1, -1);
int ans = -INF;
for (int i = 1; i <= n; i++) ans = max(ans, dp[i]);
printf("%d\n", ans);
return 0;
}
/*
7
-1 -1 -1 1 1 1 0
1 4
2 5
3 6
4 7
5 7
6 7
*/