https://vjudge.net/problem/HDU-1561
思路:稍微轉化一下就是有依賴的揹包問題了,當然也屬於樹形的範疇。這裏就說一下怎麼轉化,認爲每一個城堡的體積都是,揹包的總體積爲即可,當然有個細節要注意,就是點的體積是。
關於有依賴的揹包問題,可以看我這篇博客的介紹:
https://blog.csdn.net/xiji333/article/details/104226993
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=205;
struct Edge
{
int to,nxt;
}edge[maxn];
int n,m,tot;
int head[maxn],val[maxn],dp[maxn][maxn];
inline void addedge(int u,int v)
{
edge[++tot].to=v,edge[tot].nxt=head[u],head[u]=tot;
}
void dfs(int u)
{
int v;
int w=1;
if(u==0)
w=0;
for(int i=head[u];i;i=edge[i].nxt)
{
v=edge[i].to;
dfs(v);
for(int j=m-w;j>=1;j--)
for(int k=j;k>=1;k--)
dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]);
}
for(int i=m;i>=w;i--)
dp[u][i]=dp[u][i-w]+val[u];
}
int main()
{
while(~scanf("%d%d",&n,&m)&&(n!=0||m!=0))
{
tot=0;
memset(head,0,sizeof(head));
memset(dp,0,sizeof(dp));
int t;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&t,&val[i]);
addedge(t,i);
}
dfs(0);
printf("%d\n",dp[0][m]);
}
return 0;
}