1 /*2 depending on the relationship, you can build a tree3 Dp[i][j] Indicates the maximum value of the first node selected J4 Dp[i][j]=max (Sigma (Dp[c[i][ki]))5 Sigma (Dp[c[i][ki]]) indicates the maximum number of J points selected from the son node of I6 */7 /*#include <iostream>8 #include <cstdio>9 #include <cstring>Ten #include <vector> One using namespace std; A - const int maxn=205; - int DP[MAXN][MAXN]; the int VAL[MAXN],N,M,NUM[MAXN]; - vector<int> F[MAXN]; - inline int max (int a,int b) {return a>b?a:b;} - + void dfs1 (int u,int id,int s1,int s2) - { + if (s1>m+1 | | s1>num[u]) A return; at if (id==f[u].size ()) - { - Dp[u][s1]=max (DP[U][S1],S2); - return; - } - for (int i=0;i<=num[f[u][id]];i++) in DFS1 (U,id+1,s1+i,s2+dp[f[u][id]][i]); - return; to } + - void Dfs (int u) the { * if (f[u].size () ==0) $ {Panax Notoginseng dp[u][1]=val[u];num[u]=1; - return; the } + int temp=0; A for (int i=0;i<f[u].size (); i++) the { + int v=f[u][i]; - Dfs (v); $ Temp+=num[v]; $ } - num[u]=temp; - Dp[u][1]=val[u]; the DFS1 (u,0,1,dp[u][1]); - return;Wuyi } the int main () - { Wu int i,a; - while (~scanf ("%d%d", &n,&m), n+m) About { $ For (i=0;i<=n;i++) f[i].clear (); - val[0]=0; - For (i=1;i<=n;i++) - { A scanf ("%d%d", &a,val+i); + F[a].push_back (i); the } - m++; $ memset (Dp,0,sizeof (DP)); the memset (num,0,sizeof (num)); the DFS (0); the printf ("%d\n", Dp[0][m]); the } - return 0; in } the */ the /* About The above code did not prune, the idiot forgot to use 0-1 backpack optimization. the */ the#include <iostream> the#include <cstdio> +#include <cstring> -#include <vector> the using namespacestd;Bayi the Const intmaxn=205; the intDP[MAXN][MAXN]; - intval[maxn],n,m; -vector<int>F[MAXN]; theInlineintMaxintAintb) {returnA>b?a:b;} the the voidDfsintUintsum) the { -dp[u][1]=Val[u]; the if(m<=1)return; the for(intI=0; I<f[u].size (); i++) the {94 intv=F[u][i]; theDFS (v,sum-1); the for(intj=sum;j>=2; j--) the {98 for(intk=1; k<j;k++) AboutDp[u][j]=max (dp[u][j],dp[u][j-k]+dp[v][k]); - }101 }102 return ;103 }104 intMain () the {106 intI,a;107 while(~SCANF ("%d%d", &n,&m), n+m)108 {109 for(i=0; i<=n;i++) f[i].clear (); theval[0]=0;111 for(i=1; i<=n;i++) the {113scanf"%d%d", &a,val+i); the F[a].push_back (i); the } them++;117Memset (DP,0,sizeof(DP));118Dfs0, m);119printf"%d\n", dp[0][m]); - }121 return 0;122}
Hdu 1561 tree-shaped dp+0-1 backpack