Description |
Title Description |
Given a set of n items, each with a weight w[i] and a value v[i], determine a-to-choose the items into a knapsack so T Hat The total weight are less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can is only chosen once). |
Give you n items, and the quality of each item W[i] and value v[i]. Choosing a package means that the final quality of the backpack is small equal to the upper limit B and the final value is as large as possible. Find out the maximum total value. (Note that each item can only be selected once) |
input |
input |
tr>
The first line contains the integer T indicating to the number of test cases. The first line contains the integers n and B in the case of each test. Following n lines provide the information of each item. The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively. 1 <= Number of test cases <= 1 <= N <= 1 <= B, W[i] <= 1000000000 1 <= v[1]+v[2]+...+v[n] <=-up All the inputs is integers. |
The first line of input is an integer t representing the number of test samples. For each test sample, the first line consists of two integers n and b. Next there are n rows that represent information about each item. Line I contains the quality of article I w[i] and value v[i]. 1 <= test sample number <= 1 <= N <=, 1 <= B, W[i] <= 1000000000 1 <= v[1]+v[2]+. .. +v[n] <= Input is all integers. |
Output |
Output |
For each test case, output the maximum value. |
Each test sample outputs its maximum value. |
Sample Input-Enter sample |
Sample output-export example |
1 5 15 12 4 2 2 1 1 4 10 1 2 |
15 |
Exercises
The maximum mass is 1000000000, and the array is definitely not enough.
However, the total value is only 5000, we use the value as the axis to open up a one-dimensional array of residual load quality, followed by the same approach as the 01 backpack.
"Code C + +"
1#include <cstdio>2#include <cstring>3 intMain () {4 intweight[5001], T, I, J, N, B, Max_value, W, V;5scanf"%d", &t);6 7 while(t--){8scanf"%d%d", &n, &B);9memset (weight,0,sizeof(weight));Tenweight[0] = B, Max_value =0; One A for(j =0; J < N; ++j) { -scanf"%d%d", &w, &v); - for(i = max_value; I >=0; --i) { the if(Weight[i]-w > weight[i + v]) Weight[i + v] = weight[i]-W; - } - for(i = Max_value +1; I <= the; ++i)if(Weight[i]) Max_value =i; - } + -printf"%d\n", max_value); + } A return 0; at}
Fzu 2214 knapsack problem (knapsack problem)