C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
树形dp
$code$
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = N * 2;
typedef long long ll;
int n;
int w[N];
int h[N], e[M], ne[M], idx;
ll f[N]; // 状态数组
void add(int a, int b) { // 邻接表加边函数
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs(int u, int father) { // father:是从那个点下来的
f[u] = w[u];
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (j != father) { // 避免往回搜
dfs(j, u);
f[u] += max(0ll, f[j]);
}
}
}
int main() {
cin >> n;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++) cin >> w[i];
for (int i = 0; i < n - 1; i ++) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dfs(1, -1);
ll res = f[1];
for (int i = 2; i <= n; i ++) res = max(res, f[i]); // 求一下最大连通块
cout << res;
return 0;
}