HDU 4169 Wealthy Family【树形DP】

Problem Description
While studying the history of royal families, you want to know how wealthy each family is. While you have various 'net worth' figures for each individual throughout history, this is complicated by double counting caused by inheritance. One way to estimate the wealth of a family is to sum up the net worth of a set of k people such that no one in the set is an ancestor of another in the set. The wealth of the family is the maximum sum achievable over all such sets of k people. Since historical records contain only the net worth of male family members, the family tree is a simple tree in which every male has exactly one father and a non-negative number of sons. You may assume that there is one person who is an ancestor of all other family members.
Input
The input consists of a number of cases. Each case starts with a line containing two integers separated by a space: N (1 <= N <= 150,000), the number of people in the family, and k (1 <= k <= 300), the size of the set. The next N lines contain two non-negative integers separated by a space: the parent number and the net worth of person i (1 <= i <= N). Each person is identified by a number between 1 and N, inclusive. There is exactly one person who has no parent in the historical records, and this will be indicated with a parent number of 0. The net worths are given in millions and each family member has a net worth of at least 1 million and at most 1 billion.
Output
For each case, print the maximum sum (in millions) achievable over all sets of k people satisfying the constraints given above. If it is impossible to choose a set of k people without violating the constraints, print 'impossible' instead.
Sample Input
5 3 0 10 1 15 1 25 1 35 4 45 3 3 0 10 1 10 2 10
Sample Output
85 impossible
code:
View Code
#include<stdio.h>
#include<string.h>
#define maxn 150000
#define Max(a,b)(a)>(b)?(a):(b)
struct node
{
int to;
int next;;
}q[10000000];
int dp[300];
int w[maxn];
int head[maxn];
int n,m,tot;
void add(int s,int t)
{
q[tot].to=t;
q[tot].next=head[s];
head[s]=tot++;
}
int dfs(int r)
{
int flag,i,j,k,son,state;
int t=0; //保存当前子树已产生的状态数
int res[300]; //保存当前子树的背包状态
for(i=1;i<=m;i++)
dp[i]=res[i]=-1;
res[0]=dp[0]=0;
flag=1;
for(i=head[r];i;i=q[i].next)
{
flag=0;
son=q[i].to;
state=dfs(son); //找出son分支的状态数,同时将背包状态保存在dp数组中
for(j=t;j>=0;j--) //当前子树已产生的状态数
{
for(k=1;k<=state;k++) //son节点遍历的子树产生的状态数
{
if(j+k>m) break;
res[k+j]=Max(res[k+j],dp[k]+res[j]);
}
}
t+=state; //俩部分组合完之后再将v分支的状态数加到当前子树上
}
if(flag) t++; //叶子节点
res[1]=Max(res[1],w[r]);
for(i=0;i<=m;i++)
dp[i]=res[i];
return t; //返回当前子树产生的状态总数
}
int main()
{
int root,x,wi,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,0,sizeof(head));
tot=1;
for(i=1;i<=n;i++)
{
scanf("%d%d",&x,&w[i]);
if(x==0)
root=i;
add(x,i);
}
dfs(root);
if(dp[m]==-1)
printf("impossible\n");
else
printf("%d\n",dp[m]);
}
return 0;
}


 
posted @ 2012-04-02 23:38  'wind  阅读(404)  评论(0编辑  收藏  举报