输入:
7
-1 -1 -1 1 1 1 0
1 4
2 5
3 6
4 7
5 7
6 7
输出:
3
代码如下:
#include <iostream>
#include <vector>
using namespace std;
const int N = 100010;
typedef long long LL;
LL ans;
vector<LL>t[N];
LL w[N];void dfs(int root, int fa) {for (int i = 0; i < t[root].size(); i++) {int child = t[root][i];if (child == fa)continue;dfs(child, root);if (w[child] > 0)w[root] += w[child];}ans = max(ans, w[root]);
}int main() {int n;cin >> n;//节点个数for (int i = 1; i <= n; i++)cin >> w[i];//节点权值for (int i = 1; i <= n - 1; i++) {int a, b;cin >> a >> b;t[a].push_back(b);t[b].push_back(a);}dfs(1,-1);//假设节点1为根节点,没有父节点,用-1表示cout << ans << endl;return 0;
}