HDU1520 Anniversary party —— 树形DP

来源:互联网 发布:使命召唤 知乎 编辑:程序博客网 时间:2024/05/17 03:17

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1520


Anniversary party

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12366    Accepted Submission(s): 5009


Problem 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 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
711111111 32 36 47 44 53 50 0
 

Sample Output
5
 

Source
Ural State University Internal Contest October'2000 Students Session



题解:

dp[u][state]:结点u其状态为state(0或1,即不放和放)的最大值。

状态转移:

1.如果当前结点不放,那么它的子结点放不放都行,所以两者取其大。

2.如果当前结点放,那么它的子节点只能不放。




代码如下:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <vector>#include <cmath>using namespace std;typedef long long LL;const int INF = 2e9;const LL LNF = 9e18;const int MOD = 1e9+7;const int MAXN = 1e4+10;int val[MAXN], hav_fa[MAXN], dp[MAXN][2];vector<int>son[MAXN];int dfs(int u){    dp[u][0] = 0;   //不放,初始化为0    dp[u][1] = val[u];  //放,初始化为本身的值    for(int i = 0; i<son[u].size(); i++)    {        int v = son[u][i];        dfs(v);     //递归其子树        dp[u][0] += max(dp[v][0], dp[v][1]);    //如果不放,那么它的子节点放不放都行,所以取其大。        dp[u][1] += dp[v][0];   //如果放,那么它的子节点不能放    }    return max(dp[u][0], dp[u][1]);     //返回最大值}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        for(int i = 1; i<=n; i++)            son[i].clear(), hav_fa[i] = 0;        for(int i = 1; i<=n; i++)            scanf("%d",&val[i]);        int u, v;        while(scanf("%d%d",&v,&u) && (v || u))        {            son[u].push_back(v);            hav_fa[v] = 1;        }        for(int i = 1; i<=n; i++)   //找到根节点,然后深搜            if(!hav_fa[i])                cout<< dfs(i) <<endl;    }}


原创粉丝点击