题面 题解 代码 #include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const int N = 1e5 + 10, M = N * 2; int n; ll w[N]; ll 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) { f[u] = w[u]; for (int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if(j==father) continue; dfs(j, u); f[u] += max(0ll, f[j]); } } int main() { memset(h, -1, sizeof h); cin >> n; 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 << endl; return 0; }