Tree grouping backpack model,
That is, each child choose one state tree, state f [x] [y] y represents a maximum value of selected sub-tree rooted at x, how the election has not affected
Note that y> = 1 then x must be selected, i.e., x must chose, y can be selected from its child nodes i.e.
Forests also need to establish a virtual lesson even to the point N + 1 without first lesson
#include<iostream> #include<cstdio> #define ri register int #define u int namespace opt { inline u in() { u x(0),f(1); char s(getchar()); while(s<'0'||s>'9') { if(s=='-') f=-1; s=getchar(); } while(s>='0'&&s<='9') { x=(x<<1)+(x<<3)+s-'0'; s=getchar(); } return x*f; } } using opt::in; #define NN 305 namespace mainstay { u N,M,cnt,h[NN],v[NN],id[NN],f[NN][NN]; struct node{ u to,next; }a[NN]; inline void add(const u &x,const u &Y) { A [ ++ CNT] .to = Y, A [CNT] .next = H [X], H [X] = CNT; } void DFS ( const U & X) { for (RI I (H [ X]); I; I = A [I] .next) { U _y (A [I] .to); DFS (_y); for (RI J (M); J> = . 1 ; - J) { for (RI K ( 0 ); K <= J; ++ K) {// do not understand the words of the book and blue (that is to reverse was true), so too may the positive sequence enumeration F [X] [J] = :: max STD (F [X] [J], F [X] [JK] + F [_y] [K]); } } } IF (X ^ (N + . 1 )) { for(ri i(M);i>=1;--i){ f[x][i]=f[x][i-1]+v[x]; } } } inline void solve(){ N=in(),M=in(); for(ri i(1);i<=N;++i){ u _a(in()),_b(in()); v[i]=_b; if(_a) add(_a,i); else add(N+1,i); } dfs(N+1); std::cout<<f[N+1][M]; } } int main() { //freopen("x.txt","r",stdin); std::ios::sync_with_stdio(false); mainstay::solve(); }