This is the same idea as the previous question, but the size of the backpack is different.
[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <vector>
Using namespace std;
Int N, M, v [3010];
Vector <int> son [3010]; // records son nodes
Vector <int> cost [3010]; // Record cost
Int dp [3010] [3010];
Int dfs (int n ){
Int sum = 0, len = son [n]. size ();
Dp [n] [0] = 0;
If (n> N-M ){
Dp [n] [1] = v [n];
Return 1;
}
For (int I = 0; I <len; I ++)
{
Int num = dfs (son [n] [I]);
Sum + = num;
For (int j = sum; j> = 1; j --)
For (int k = 1; k <= num & k <= j; k ++)
If (dp [n] [j] <dp [n] [j-k] + dp [son [n] [I] [k]-cost [n] [I ])
Dp [n] [j] = dp [n] [j-k] + dp [son [n] [I] [k]-cost [n] [I];
}
Return sum;
}
Int main ()
{
Int I, j, k, a, c, ans;
While (scanf ("% d", & N, & M )! = EOF)
{
Ans = 0;
Memset (dp,-12345, sizeof (dp ));
For (I = 0; I <= N; I ++) son [I]. clear ();
For (I = 1; I <= N-M; I ++ ){
Scanf ("% d", & k );
For (j = 1; j <= k; j ++ ){
Scanf ("% d", & a, & c );
Son [I]. push_back ();
Cost [I]. push_back (c );
}
}
For (I = N-M + 1; I <= N; I ++) {// originally written for (I = 1; I <= M; I ++ ).
Scanf ("% d", & v [I]);
// Printf ("% d", v [I]);
} // Printf ("~ \ N ");
Dfs (1 );
For (I = M; I> = 1; I --)
If (dp [1] [I]> = 0 ){
Printf ("% d \ n", I );
Break;
}
}
Return 0;
}
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <vector>
Using namespace std;
Int N, M, v [3010];
Vector <int> son [3010]; // records son nodes
Vector <int> cost [3010]; // Record cost
Int dp [3010] [3010];
Int dfs (int n ){
Int sum = 0, len = son [n]. size ();
Dp [n] [0] = 0;
If (n> N-M ){
Dp [n] [1] = v [n];
Return 1;
}
For (int I = 0; I <len; I ++)
{
Int num = dfs (son [n] [I]);
Sum + = num;
For (int j = sum; j> = 1; j --)
For (int k = 1; k <= num & k <= j; k ++)
If (dp [n] [j] <dp [n] [j-k] + dp [son [n] [I] [k]-cost [n] [I ])
Dp [n] [j] = dp [n] [j-k] + dp [son [n] [I] [k]-cost [n] [I];
}
Return sum;
}
Int main ()
{
Int I, j, k, a, c, ans;
While (scanf ("% d", & N, & M )! = EOF)
{
Ans = 0;
Memset (dp,-12345, sizeof (dp ));
For (I = 0; I <= N; I ++) son [I]. clear ();
For (I = 1; I <= N-M; I ++ ){
Scanf ("% d", & k );
For (j = 1; j <= k; j ++ ){
Scanf ("% d", & a, & c );
Son [I]. push_back ();
Cost [I]. push_back (c );
}
}
For (I = N-M + 1; I <= N; I ++) {// originally written for (I = 1; I <= M; I ++ ).
Scanf ("% d", & v [I]);
// Printf ("% d", v [I]);
} // Printf ("~ \ N ");
Dfs (1 );
For (I = M; I> = 1; I --)
If (dp [1] [I]> = 0 ){
Printf ("% d \ n", I );
Break;
}
}
Return 0;
}