D - 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

题意:

在一个聚会中,由于学校的管理系统,所以形成了一棵树,树根是校长。

为了使每个人高兴,那么他的雇主不能在场,求出最大高兴的人数。

思路:

这道题因为数据太大,所以要用vector容器,然后存储所有的子节点;

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

i不去聚会:dp[i][0]+=max(dp[j][0],dp[j][1]);    i不去,所以它的下属可以去或者是不去;

i去聚会:dp[i][1]+=dp[j][0];     i去聚会,所以下属不能去聚会;

注意是+=,因为一个父节点有多个子节点;

代码如下:

#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
#define N 6010

int book[N];
int dp[N][2];
int n;

vector<int>a[N];

void dfs(int k)
{
    int i,t;
    book[k]=1;
    for(i=0; i<a[k].size(); i++)
    {
        t=a[k][i];
        if(book[t]==0)
        {
            dfs(t);
            dp[k][1]+=dp[t][0];
            dp[k][0]+=max(dp[t][0],dp[t][1]);
        }
    }
}

int main()
{
    while(~scanf("%d",&n))
    {
        memset(book,0,sizeof book);
        int i,j;
        for(i=0; i<=n; i++)
            a[i].clear();
        for(i=1; i<=n; i++)
        {
            scanf("%d",&dp[i][1]);
            dp[i][0]=0;
        }
        int aa,bb;
        while(~scanf("%d%d",&aa,&bb))
        {
            if(aa==0&&bb==0)
                break;
            a[aa].push_back(bb);
            a[bb].push_back(aa);
        }
        dfs(1);
        printf("%d\n",max(dp[1][0],dp[1][1]));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/titi2018815/article/details/82054565