HDU 1520 Anniversary party【树形DP】

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
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,求最大权值。
分析: 基础树形DP,多叉转二叉采用左儿子又兄弟法。
 f[i][1]表示以i为根节点的树并且包含根节点的最优值;
 f[i][0]表示以i为根节点的树并且不包含根节点的最优值;
 状态转移方程:f[i][0]=max(f[tree[i].son][0],f[tree[i].son][1]);
              f[i][1]=tree[i].gr+f[tree[i].son][0];
code:
View Code
#include<stdio.h>
#include<string.h>
#define clr(x)memset(x,0,sizeof(x))
#define max(a,b)(a)>(b)?(a):(b)
int k,l,n,f[6000][2];
bool v[6000];
struct node
{
int ls,rs,wi;
}tree[6000];
void dp(int r)
{
int son;
if(!tree[r].ls&&!tree[r].rs)
f[r][1]=tree[r].wi;
else
{
f[r][1]=tree[r].wi;
son=tree[r].ls;
while(son)
{
dp(son);
f[r][1]+=f[son][0];
f[r][0]+=max(f[son][0],f[son][1]);
son=tree[son].rs;
}
}
}
int main()
{
int i;
while(scanf("%d",&n)!=EOF)
{
clr(v); clr(tree); clr(f);
for(i=1;i<=n;i++)
scanf("%d",&tree[i].wi);
while(scanf("%d%d",&l,&k),l+k)
{
tree[l].rs=tree[k].ls;
tree[k].ls=l;
v[l]=1;
}
for(i=1;i<=n;i++)
if(!v[i])
{
dp(i);
break;
}
printf("%d\n",max(f[i][0],f[i][1]));
}
return 0;
}
 
 
 
posted @ 2012-03-22 00:10  'wind  阅读(376)  评论(0编辑  收藏  举报