C++求树子节点权重最大的和

 

#include <iostream>
#include <vector>

using namespace std;
int n;
const int MaxN = 1e5;
long long w[MaxN + 1];
long long ans;
vector<int> g[MaxN + 1];

void dfs(int root, int fa) {
    for (int i = 0; i < g[root].size(); ++i) {
        int son = g[root][i];
        if (son != fa) {
            dfs(son, root);
            if (w[son] > 0)
                w[root] += w[son];
        }
    }
    if (w[root] > ans) ans = w[root];
}

void _cin() {
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> w[i];
    }
    for (int j = 0; j < n - 1; ++j) {
        int v, u;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
}

int main() {
    _cin();
    dfs(1, 0);
    cout << ans << endl;
    return 0;
}

posted @ 2020-07-08 18:31  HDAWN  阅读(456)  评论(0编辑  收藏  举报