C++树形DP基础例题—————没有上司的晚会

该博客介绍了如何使用C++解决一个树形动态规划问题,目标是构建一个总统晚会的嘉宾名单,使得在员工与其直接上级不能同时出席的情况下,总体的欢乐度(conviviality rating)最大化。博主提供了问题背景、输入输出说明,并详细解释了思路,通过定义状态f[i][0]和f[i][1]分别表示节点i是否出席的情况,以及遍历森林求解最大值的方法。
摘要由CSDN通过智能技术生成

题目描述:

Background

The president of the Ural State University is going to make an 80'th Anniversary party. The university has a hierarchical structure of employees; that is, the supervisor relation forms a tree rooted at the president. Employees are numbered by integer numbers in a range from 1 to N, The personnel office has ranked each employee with a conviviality rating. In order to make the party fun for all attendees, the president does not want both an employee and his or her immediate supervisor to attend.

Problem

Your task is to make up a guest list with the maximal conviviality rating of the guests.

输入:

The first line of the input contains a number N. 1 ≤ N ≤ 6000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from –128 to 127. After that the supervisor relation tree goes. Each line of the tree specification has the form

<L> <K>

which means that the K-th employee is an immediate supervisor of L-th employee. Input is ended with the line

0 0

输出:

The output should contain the maximal total rating of the guests.

输入与输出样例:

思路分析:

我们可以这样想,他的顶头上司(子节点的父亲)一去就不能去了。所以我们可以这样定义其的状态。

设f[i][0]为第i个节点没有来,f[i][1]是第i个节点来了。

当第i个节点没来,他的儿子就又可以为所欲为了(为什么是又,O(∩_∩)O~),所以为f[i][0]=\sum_{j=1}^{m}\;\;max(f[j][0],f[j][1])(j\in son_{i})

当第i个节点来了,他的儿子就不能来了,就是f[i][0]=\sum_{j=1}^{m}\;\;f[j][0]\;\;(j\in son_{i})

因为这也许是一个森林,所以就要多次遍历求最大值。

代码实现:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
int n,m,dp[6005][2],f[6005],ans,fa[6005];
vector<int>G[6005];
int read()
{
    int x=0,f=1;
    char s=getchar();
    while(s<'0'||s>'9')
    {
        if(s=='-')
            f=-1;
        s=getchar();
    }
    while(s>='0'&&s<='9')
    {
        x*=10;
        x+=s-'0';
        s=getchar();
    }
    return x*f;
}
void dfs(int x,int fa)
{
    for(int i=0;i<G[x].size();i++)
    {
        dfs(G[x][i],x);
        dp[x][0]+=max(dp[G[x][i]][0],dp[G[x][i]][1]);
        dp[x][1]+=dp[G[x][i]][0];
    }
    dp[x][1]+=f[x];
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        f[i]=read();
    int a,b;
    while(scanf("%d%d",&a,&b))
    {
        if(a==0)
            break;
        G[b].push_back(a);
        fa[a]=b;
    }
    for(int i=1;i<=n;i++)
    {
        if(!fa[i])
        {
            dfs(i,fa[i]);
            ans=max(dp[i][1],max(dp[i][0],ans));
        }
    }
    printf("%d",ans);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值