天天看点

Anniversary party HDU - 1520(树形dp)

传送门

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 T 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个人中选出一些人来参加party,这n个人不能有直接的上下级关系,每个人有他的价值,要求最后获得的最大的总价值是多少?

基础的树形dp吧,我们用dp[i][0]表示i没有来,用dp[i][1]表示i过来了,那么状态转移方程也是很明显的,首先上机若果来了,则他的下级一定不会过来,反之,他的下级可以过来或者不过来。

dp[fa][0] += max(dp[G[fa][i]][1] , dp[G[fa][i]][0]);

dp[fa][1] += dp[G[fa][i]][0];

#include<iostream>
#include<stdio.h>
#include<string>
#include<math.h>
#include<queue>
#include<vector>
#include<string.h>
#include<iterator>
using namespace std;
const int inf = 0x3f3f3f3f;
int val[6005];
int fa[6005];
int dp[6005][2];
vector<int> G[6005];
void dfs(int fa) {
    for(int i = 0 ; i < G[fa].size() ; i ++) {
        int son = G[fa][i] ;
        dfs(son) ;
    }
    for(int i = 0 ; i < G[fa].size() ; i ++) {
        dp[fa][0] += max(dp[G[fa][i]][1] , dp[G[fa][i]][0]);
        dp[fa][1] += dp[G[fa][i]][0];
    }
}
int main()
{
    int n ;
    while(~scanf("%d" , &n)) {
        memset(fa , 0 , sizeof(fa));
        memset(dp , 0 , sizeof(dp));
        for(int i = 0 ; i <= n ; i ++)
            G[i].clear();
        for(int i = 1 ; i <= n ; i ++) {
            scanf("%d" , &val[i]);
            fa[i] = i;
            dp[i][1] = val[i];
        }
        int u , v ;
        while(1){
            scanf("%d%d" , &u , &v) ;
            if(u == 0 && v == 0)
                break;
            G[v].push_back(u);
            fa[u] = v ;
        }
        int root = 1;
        while(fa[root] != root)
            root = fa[root] ;
        dfs(root);
        cout<<max(dp[root][0] , dp[root][1])<<endl;
    }
    return 0;
}