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;
}

版权声明:本文为HDawn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/HDawn/p/13268527.html