POJ 2342 Anniversary party【树形dp】【基础入门】

Description

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

题意:

一个公司要举行一个party ,让每个人参加的话就会增加一定的愉悦值,为了排除尴尬的场面,每个人和他的直接领导不能同时来参加,给你一个 n ,说明有 n 个人,然后 接着 n 行 表示 让每个人去所增加的愉悦程度,接着每行输入两个数l 和 k ,表示  k 是 l 的直属上司,直到输入为 0 0 时该组输入结束,输出所能达到的最大的欢乐值。

分析:

不会存在环,就是一个树的结构

dp[node][0]代表node不去,dp[node][1]代表node去

dp[node][1]+=dp[son][0]; ///上司去 下属不去

 dp[node][0]+=max(dp[son][1],dp[son][0]);  /// 上司不去 下属去或不去

代码:
 

#include<stdio.h>
#include<string.h>
#include<vector>
#define MAX 6000+10
using namespace std;
int dp[MAX][2],vis[MAX];///0代表不去,1代表去
vector<int>tree[MAX];   ///存储子节点
void dfs(int node)
{
    vis[node]=1;
    int i,j;
    int son;
    for(i=0;i<tree[node].size();i++)
    {
        son=tree[node][i];
        if(!vis[son])
        {
            dfs(son);
            dp[node][1]+=dp[son][0]; ///上司去 下属不去
            dp[node][0]+=max(dp[son][1],dp[son][0]);  /// 上司不去 下属去或不去
        }
    }
}
int main()
{
    int n,i;
    int root;
    int x,y;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=1;i<=n;i++)
        {
            scanf("%d",&dp[i][1]);
            dp[i][0]=0;
            vis[i]=1;
            tree[i].clear();
        }
        while(scanf("%d%d",&x,&y)&&(x!=0||y!=0))
        {
            vis[x]=0;///x为下属 标记一下
            tree[y].push_back(x);///y的下属
        }
        root=0;
        for(i=1;i<=n;i++)///查询根节点
        {
            if(vis[i])
            {
                root=i;///记录根节点
                break;
            }
        }
        memset(vis,0,sizeof(vis));
        dfs(root);
        printf("%d\n",max(dp[root][0],dp[root][1]));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lml11111/article/details/81974717