Question:
A lot of new semester will have to go to school tomorrow. Today, she decided to have a good time at night. She liked to watch cartoons. So she wants her uncle to buy some movies for her to watch tonight. Her grandfather gave her l minutes to watch cartoons. Later, she had to go to bed. Many movies numbered from 1 to n are her favorite movies. She wants her uncle to buy them for her. Each movie has a value of Val, and each movie has a time t. A lot of movies won't stop playing, but there is a strange problem that the store sells M movies (rather than less or more) to her uncle. How to Choose M movies to select the highest value from N movies and the time cost should not exceed L.
How smart you are! Please help the Executive Committee Zheng jingxian + uncle with many beautiful women.
Input data:
1 // indicates the total number of samples.
3 2 10
// The first line of each sample indicates N, M, L
11 100 // n rows of time t and value Val for each movie
1 2
9 1
Solution:
For more information about two-dimensional backpacks, see section 9.
Pay attention to initialization issues.
In the initial status, the status can be determined only when the time is 0 and the initial status is 0. other statuses should be initialized to negative infinity.
# Include <cstdio> # include <algorithm> # include <iostream> using namespace STD; Class DVD {public: int time; int val;} movie [110]; int d [1100] [110]; // * void print (int l, int m) // a function {cout <Endl; for (INT I = 0; I <= L; I ++) {for (Int J = 0; j <= m; j ++) {cout <D [I] [J] <'';} cout <Endl ;}*/INT main () {int total; scanf ("% d", & total); While (total --) {int N; // n: the number of DVDs that duoduo want buy. int m; // M: The number of DVDs that the shop can sale.int L; // L: the longest time that her grandfather allowed to watch. scanf ("% d", & N, & M, & L); For (INT I = 0; I <n; I ++) {scanf ("% d", & movie [I]. time, & movie [I]. val);} // d [I] [J] [k] indicates the maximum size of K for the first I item j minutes memset (D,-1, sizeof (d )); // unknown status for (INT I = 0; I <= L; I ++) {d [I] [0] = 0; // unique identifiable status} // print (L, M); For (INT I = 0; I <n; I ++) {for (Int J = L; j> = movie [I]. time; j --) {for (int K = m; k> = 1; k --) {If (d [J-movie [I]. time] [k-1] =-1) // unknown status obviously cannot be transferred {continue ;} if (d [J] [k] <D [J-movie [I]. time [k-1] + movie [I]. val) {d [J] [k] = d [J-movie [I]. time [k-1] + movie [I]. val ;}}// print (L, M);} If (d [l] [m] =-1) {printf ("0 \ n "); continue;} printf ("% d \ n", d [l] [m]);} return 0 ;}