/*
题目描述:给出n各城市,每个城市i有一个宝藏val[i],想要攻打城市并获得i的宝藏,需要先攻打城市pre[i],问攻打m个城市
能获得的最大的宝藏的值是多少
思路:首先根据攻打的先后关系建立一棵有根树,然后在树上进行dp
设dp[i][j]表示在i的子树中取一个包含i在内的合法形态的树(若某一点在树中则祖先在树中)能获得的宝藏的最大的值,
那么dp[fa][j] = max(dp[fa][j] , dp[fa][j - k] + d[son][k])(k从1到j-1)
那么最终答案就是dp[0][m + 1]
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-6;
const int maxn = 200 + 5 ;
int dp[maxn][maxn];
vector<int>G[maxn];
int val[maxn];
int n , m ;
void build_graph(int n)
{
int x;
for(int i = 1 ; i<= n ; i++){
scanf("%d%d", &x , &val[i]);
G[x].push_back(i);
}
}
void dfs(int root)
{
int sz = G[root].size() , nt;
dp[root][1] = val[root];
for(int i = 0 ; i<sz ; i++){
nt = G[root][i];
dfs(nt);
for(int j = n ; j >= 1 ; j--){
for(int k = 1 ; k < j ; k++){
dp[root][j] = max(dp[root][j] , dp[root][k] + dp[nt][j - k]);
}
}
}
}
int main()
{
while(scanf("%d%d", &n , &m) != EOF){
if(!n && !m) break;
mem(dp , 0);
for(int i = 0 ; i<= n ; i++)
G[i].clear();
build_graph(n);
dfs(0);
int ans = dp[0][m+1] ;
printf("%d\n",ans);
}
return 0;
}
hdu1561 the more , the better 树形dp
最新推荐文章于 2019-10-15 19:06:00 发布