Anniversary party

博客围绕庆祝大学80周年派对的员工邀请问题展开。已知员工层级关系和欢乐评分,要求安排人员使欢乐评分总和最大。这是一个DP问题,定义状态并给出状态转移方程,最后比较得出最大评分值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests' conviviality ratings.

Input

Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. 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 go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form: 
L K 
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line 
0 0 

Output

Output should contain the maximal sum of guests' ratings.

Sample Input

7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0

Sample Output

5

题意:有n个人,接下来n行对应每个人的欢乐评分,有n组对应关系,如果某个人去了,那么它的领导就不能去,如果这个人不去,它的领导去不去都行,反之同理,问怎样安排欢乐评分最高输出这个评分最高的值。

思路:这个题是dp问题,dp[i][0]表示第i个人不去,dp[i][1]表示第i个人去.,如果上司boss去参加舞会的话,i只能不去了,如果上司boss不去的话,i可去可不去,所以状态转移方程为:

dp[boss][1]=dp[boss][1]+dp[i][0];

dp[boss][0]=dp[boss][0]+max(dp[i][0],dp[i][1])

最后比较一下那个值最大输出即可,代码如下:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n;                            //dp[i][0] 第i个人不去的话能取得最大值,dp[i][1]第i个人去的话能去的最大值
int f[6020],dp[6020][2],book[6020];
void dfs(int boss)
{
    book[boss]=1;      //这个节点为上司时已经用过了
    for(int i=1;i<=n;i++)
    {
        if(!book[i]&&f[i]==boss) //找boss的下属
        {
            dfs(i); //由下属递归下去
            dp[boss][1]=dp[boss][1]+dp[i][0];  //如果上司boss去参加舞会的话,i只能不去了
            dp[boss][0]=dp[boss][0]+max(dp[i][0],dp[i][1]); //如果上司boss不去的话,i可去可不去,因此要取最大值
        }
    }
}
int main()
{
    while(~scanf("%d",&n))
    {
        int i,x,y,boss=0;
        memset(book,0,sizeof(book));
        memset(dp,0,sizeof(dp));
        memset(f,0,sizeof(f));
        for(i=1; i<=n; i++)
            scanf("%d",&dp[i][1]);//每一个人都去的时候每个人的欢乐度
        while(~scanf("%d%d",&x,&y)&&(x||y))
        {
            f[x]=y; //x的上司是y
            boss=y;  //记录任意一个上司
        }
        dfs(boss); //通过递归求最大值
        printf("%d\n",max(dp[boss][0],dp[boss][1]));//由boss开始递归
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值