题解 | 派对的最大快乐值

派对的最大快乐值

https://www.nowcoder.com/practice/a5f542742fe24181b28f7d5b82e2e49a

#include<bits/stdc++.h>
using namespace std;

class TreeNode {
  public:
    int happy;
    vector<TreeNode*> next;
    TreeNode(int h): happy(h) {}
};

/*class Max {
  public:
    int no;
    int yes;
    Max(int n, int y): no(n), yes(y) {}
};*/

/*Max getMax(TreeNode* root) {
    if (root->next.empty()) return Max(0, root->happy);
    int n = 0, y = root->happy;
    for (auto r : root->next) {
        auto k = getMax(r);
        y += k.no;
        n += max(k.yes, k.no);
    }
    return Max(n, y);
}*/


struct ReturnType {
    int has_value;
    int no_value;
    ReturnType(int has, int no) {
        has_value = has;
        no_value = no;
    }
};


ReturnType dfs(TreeNode* root) {
    int has_res = root->happy;
    int no_res = 0;
    for (int i = 0; i < root->next.size(); ++i) {
        if (!root->next[i]) {
            continue;
        }
        ReturnType node = dfs(root->next[i]);
        has_res += node.no_value;
        no_res += max(node.has_value, node.no_value);
    }
    ReturnType res(has_res, no_res);
    return res;
}



int main() {
    int n, root;
    cin >> n >> root;
    vector<TreeNode*> happy(n);
    int t, u, v;
    for (int i = 0; i < n; ++i) {
        cin >> t;
        happy[i] = new TreeNode(t);
    }
    for (int i = 1; i < n; ++i) {
        cin >> u >> v;
        happy[u - 1]->next.push_back(happy[v - 1]);
    }
    auto res = dfs(happy[root - 1]);
    cout << max(res.has_value, res.no_value) << endl;
    //auto x = getMax(happy[root - 1]);
    //cout << max(x.no, x.yes) << endl;
    return 0;
}

全部评论

相关推荐

92Y:泡成巨人观了吧
投递百度等公司10个岗位
点赞 评论 收藏
分享
勇敢的90后想交流:我愿意付费上班,楼主你就安心字节待着吧,我是真的喜欢上班
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务