标签:hdu 1561 the more the better 树形dp+01背包
Description
Input
Output
Sample Input
3 2 0 1 0 2 0 3 7 4 2 2 0 1 0 4 2 1 7 1 7 6 2 2 0 0
Sample Output
5 13
技巧:设置0这个根节点,将森林转化为树
状态:dp[i][j]:以i为根,取子树下j个点的最大值
状态方程:dp[u][j]=max(dp[u][j],dp[u][k]+dp[v][j-k];
#include<iostream>
using namespace std;
#include<cstdio> #include<algorithm> #include<cstring> #include<vector> #define maxn 205 #define inf 0x3f3f3f3f int n,m; int dp[maxn][maxn]; vector<int>g[maxn]; bool vis[maxn]; void dfs(int u){ for(int i=0;i<g[u].size();i++){ int v=g[u][i]; if(g[v].size()>0) dfs(v); for(int j=m;j>1;j--) for(int k=1;k<j;k++){ dp[u][j]=max(dp[u][j],dp[u][k]+dp[v][j-k]); } } } int main() { int u,v,c; freopen("in.txt","r",stdin); while(~scanf("%d%d",&n,&m)&&n&&m){ m++; memset(dp,0,sizeof dp); for(int i=1;i<=n;i++){ scanf("%d%d",&u,&c); g[u].push_back(i); for(int j=1;j<=m;j++){ dp[i][j]=c; } } dfs(0); printf("%d\n",dp[0][m]); for(int i=0;i<=n;i++){ g[i].clear(); } } }
hdu 1561 The more, The Better(树形dp+01背包)
标签:hdu 1561 the more the better 树形dp+01背包
原文地址:http://blog.csdn.net/u013497977/article/details/44700001