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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章