题目分析:这道题就是一道非常经典的树状dp。
树状dp和普通dp有何区别呢?其实树状dp就是在一棵树上进行背包问题。因为在题目中多了前后级关系(即先做……才能做……),所以我们才要用树的结构类型。
题目难点:
(1)树的存储:前向星
(2)存在多棵树:因为如果没有上一级的话会把上一级写作0,所以我们可以把0当作第一级,把几棵树当作0的子树。
(3)树的遍历:到底是选择先序遍历还是后序遍历?
应该选择后序遍历,因为后序遍历可以让最后的答案存储在根节点处。
参考程序:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,tot=0;
int head[100005],maxbook[1005],dp[1005][1005];
struct data1
{
int dis,to,next;
}a[100005];
void add_edge(int x,int y,int z)
{
a[++tot].dis = z;
a[tot].to = x;
a[tot].next = head[y];
head[y] = tot;
}
void tranvers(int begin)
{
for(int i=head[begin];i!=0;i=a[i].next)
{
tranvers(a[i].to);
}
for(int i=head[begin];i!=0;i=a[i].next)
{
maxbook[begin] += maxbook[a[i].to] + 1;
for(int k=maxbook[begin]-1;k>=0;k--)
for(int j=0;j<=maxbook[a[i].to];j++)
{
dp[begin][j+k+1] = max(dp[begin][j+k+1] , dp[begin][k] + dp[a[i].to][j] + a[i].dis);
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
int k,s;
cin>>k>>s;
add_edge(i+1,k+1,s);
}
tranvers(1);
cout<<dp[1][m];
/* for(int i=1;i<=n+1;i++) cout<<maxbook[i]<<endl;
for(int i=1;i<=n+1;i++,cout<<endl)
for(int j=1;j<=m;j++) cout<<dp[i][j]<<" ";*/
return 0;
}