Anniversary party

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个人打算搞事情,每个人都有自己的能力值,这些人的编号是从1~N,然后给你一些关系,让你选择一些人达到最大的能力值(前提啊,这些人当中不能出现两个有关系的人,换成树形建立的话就是父亲节点和子节点不能同时出现)。

本以为是贪心,结果是dp,我服了

dp[i][0] 为不选择第i人得到的能力值,dp[i][1] 为选择第i人得到的能力值

假设 j 是第i个人的下属, 那么有转移方程  :

dp[i][0]+=max( dp[j][0],dp[j][1]);  因为一个父节点有多个子节点

dp[i][1]+=dp[j][0];然后你遍历一遍就可以了。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
using namespace std;
bool book[6010];
int dp[6010][2];
vector<int>a[6010];
void dfs(int x)
{
    for(int i=0; i<a[x].size(); i++)
    {
        int y=a[x][i];
        dfs(y);
        dp[x][0]+=max(dp[y][1],dp[y][0]);
        dp[x][1]+=dp[y][0];
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n)&&n)
    {
        memset(dp,0,sizeof(dp));
        memset(book,0,sizeof(book));
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&dp[i][1]);
        }
        int x,y;
        while(~scanf("%d%d",&x,&y)&&x+y)
        {

            a[y].push_back(x);
            book[x]=1;
        }
        for(int i=1; i<=n; i++)
        {
            if(!book[i])
            {
                dfs(i);
                printf("%d\n",max(dp[i][1],dp[i][0]));
                break;
            }
        }
        for(int i=1; i<=n; i++)
            a[i].clear();
    }
    return 0;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值