hdu 1561 The more, The Better
http://acm.hdu.edu.cn/showproblem.php?pid=1561
同hdu1011只是这里做的小处理是将0点加入,将原来的森林变成了树,这样就可以按照树形dp展开来做了。。
dp[i][j]表示从i点往后占领j个城市所获得的总的最多宝物
dp[i][j]=max(dp[i][j],dp[i][j-k]+dp[son[i]][k])
View Code
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#define maxn 207
using namespace std;
int val[maxn],visit[maxn],dp[maxn][maxn];
vector<int>g[maxn];
int n,m;
void dfs(int pos)
{
int i,j;
visit[pos] = true;
for (i = 1; i <= m; ++i)
{
dp[pos][i] = val[pos];
}
for (i = 0; i < g[pos].size(); ++i)
{
int p = g[pos][i];
if(visit[p])
continue;
dfs(p);
for (j = m; j >= ( pos==0 ? 0:1); --j)
{
for (int k = 1; j + k <= m; ++k)
if(dp[p][k])
dp[pos][j+k] = max(dp[pos][j+k],dp[pos][j]+dp[p][k]);
}
}
}
int main()
{
//freopen("d.txt","r",stdin);
int i,a;
while(scanf("%d%d",&n,&m))
{
memset(val,0,sizeof(val));
if(!n&&!m) break;
for (i = 0; i <= n; ++i)
g[i].clear();
for (i = 1; i <= n; ++i)
{
scanf("%d%d",&a,&val[i]);
g[a].push_back(i);//有向图
}
memset(dp,0,sizeof(dp));
memset(visit,false,sizeof(visit));
dfs(0);
printf("%d\n",dp[0][m]);
}
return 0;
}