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

题目描述:

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

猜你喜欢

转载自blog.csdn.net/weixin_43810158/article/details/88234462