没有上司的舞会 题解

题目描述

http://oj.yogeek.cn/problem/z5041

算法思想

没有上司的舞会这一题是个典型的树形动态规划
对于每一个人,都有来与不来两种情况
简单思考即可得到答案

时间复杂度

O ( N ) O(N)

参考代码

#include <iostream>
#include <cstring>

using namespace std;
const int N = 6010;
int dp[N][2], happy[N];
int h[N], ne[N], e[N], idx;
int fa[N];
void add(int x, int y)
{
    e[idx] = y;
    ne[idx] = h[x];
    h[x] = idx;
    idx++;
}
void dfs(int u)
{
    dp[u][1] = happy[u];
    for(int i = h[u]; i != -1; i = ne[i])
    {
        int s = e[i];
        dfs(s);
        dp[u][0] += max(dp[s][0], dp[s][1]);
        dp[u][1] += dp[s][0];
    }
}
int main(){
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", &happy[i]);
    memset(h, -1, sizeof h);
    for(int i = 0; i < n - 1; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        add(b, a);
        fa[a] = b; 
    }
    int root = 1;
    while(fa[root]) root++; 
    dfs(root);
    printf("%d\n", max(dp[root][0], dp[root][1]));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ablyh/article/details/107660034
今日推荐