树形DP入门

来源:互联网 发布:淘宝装修工具2.1 编辑:程序博客网 时间:2024/06/04 19:29

Anniversary party

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


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
 

/*这道题题意很简单,就是子节点不能与父节点同时被选中,每个节点都有相应的权值,问怎么选达到的值最大?思路也很明显,就是到了某个节点,我选我自己啊还是选我的子节点,然后这就是一个裸的树形DP。 一般树形DP就是和搜索联系在一起使用的。 */#include<stdio.h>#include<string.h>#include<iostream>#include<vector>#include<algorithm>using namespace std;const int MAXN=6050;vector<int>vec[MAXN];int f[MAXN];int hap[MAXN];int dp[MAXN][2];void dfs(int root){    int len=vec[root].size();    dp[root][1]=hap[root];        for(int i=0;i<len;i++)       dfs(vec[root][i]);           for(int i=0;i<len;i++)    {        dp[root][0]+=max(dp[vec[root][i]][1],dp[vec[root][i]][0]);        dp[root][1]+=dp[vec[root][i]][0];    }}int main(){    int n;    int a,b;    while(scanf("%d",&n)!=EOF)    {        for(int i=1;i<=n;i++)        {            scanf("%d",&hap[i]);            vec[i].clear();            f[i]=-1;//树根标记            dp[i][0]=dp[i][1]=0;        }        while(scanf("%d%d",&a,&b))        {            if(a==0&&b==0)break;            f[a]=b;            vec[b].push_back(a);        }        a=1;        while(f[a]!=-1)a=f[a];//找到树根        dfs(a);        printf("%d\n",max(dp[a][1],dp[a][0]));    }    return 0;}