题解 | 派对的最大快乐值

派对的最大快乐值

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

全部评论

相关推荐

头像
11-03 16:48
已编辑
百度_高级研发工程师
事实是检验真理的唯一标准。&nbsp;无论我们怎么去说,去讲述,去证明,都抵不过一个offer来得实在,无论我们怎么去复现求职中的摸爬滚打、扒皮抽筋、狼狈不堪,都抵不过你在简历写上大厂的名字(外包不算)。&nbsp;所以在我求职期间,我什么话都不说,什么话都不讲,因为没有意义,虽然我总讲过程才是意义,但只有当你上岸的那一刻,你才有资格回想在水里的挣扎,只有等你出了山,你才知道山的全貌。&nbsp;我为什么一定要离开华为OD,难道它不稳定吗,不能赚钱吗。为了证明自己,那肯定有的。其实更多的是印证我的认知是否真的正确。&nbsp;(给不了解我的人交代一下背景,在下双非一本,gap一年,华为OD外包,摸爬滚打4个月,艰难上岸百度正编)一、...
先锋战士:说得很真诚。鄙视链自古有之,学历,家庭背景,财富,权利。从小有之,小学羡慕那些当班委的,中学羡慕那些学生会的,高中羡慕尖子班拿教学金的,大学羡慕高绩点,毕业了羡慕进大厂的。工作了,又羡慕高职级的,再后来又羡慕别人早早结婚的。我想表达的观点很简单,无论是华为od还是百度,都是经历,没有孰高孰低,为了抵达下一个风景,总会付出更多东西,但不就是人生吗?正如登山,每个阶段的山,都要想办法攀登,在博主的文字中,见到了坚持和积极寻找问题解决办法的心态
学历对求职的影响
点赞 评论 收藏
分享
美丽的95后准备进厂:第二个是外卖➕点评吧,很眼熟
点赞 评论 收藏
分享
Sigma429:极兔啊,薪资开的巨低,还在上海,索性不做笔试了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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