AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 285. 没有上司的舞会    原题链接    简单

作者: 作者的头像   福如东海 ,  2019-10-24 13:23:49 ,  所有人可见 ,  阅读 1016


1


1

算法1

(记忆化搜索) $O(n)$

dfs(node, true)表示选node的最大值, dfs(node,false)表示不选node的最大值, 为了加快速度用记忆化的方式

时间复杂度

参考文献

C++ 代码

#include <iostream>
#include <cstring>

using namespace std;

const int C = 6005;

int hi[C], h[C], ne[C], e[C], idx;
bool has_parent[C];
int dp[C][2];

void add(int x, int y) {
    ne[idx] = h[x];
    e[idx] = y;
    h[x] = idx++;
}

int dfs(int node, bool select) {
    if (dp[node][select] != -1) return dp[node][select];
    dp[node][1] = hi[node];
    dp[node][0] = 0;
    for (int i = h[node]; i != -1; i = ne[i]) {
        int j = e[i];
        dp[node][1] += dfs(j, false);
        dp[node][0] += max(dfs(j, true), dfs(j, false));
    }
    if (select) return dp[node][1];
    else return dp[node][0];
}
int main() {
    int n;
    cin >> n;
    memset(h, -1, sizeof h);
    memset(dp, -1, sizeof dp);
    for (int i = 1; i <= n; i ++) cin >> hi[i];
    int root = 1;
    for (int i = 1; i <= n - 1; i ++) {
        int l, k;
        cin >> l >> k;
        add(k, l);
        has_parent[l] = true;
    }
    for (int i = 1; i <= n; i ++)
        if (has_parent[i] == false) {root = i; break;}
    int ans = max(dfs(root, true), dfs(root, false));
    cout << ans;
    return 0;
}


0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息