Description
Given a set of n items, each with a weight w[i] and a value v[i], determine a way 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 this each item can is only chosen once).
Input
The ' The ' contains the ' the ' indicating to the number of test cases.
For the all test case, the the contains the integers n and B.
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 <= 100
1 <= N <= 500
1 <= B, W[i] <= 1000000000
1 <= v[1]+v[2]+...+v[n] <= 5000
All the inputs are integers.
Output
For each test case, output the maximum value.
Sample Input
1
5
4 2 2 1 1 4
ten
1 2
Sample Output
15
the
n items into a backpack with a capacity of B, each item has its weight and volume, ask the maximum weight can be obtained.
train of Thought
At a glance it's just a normal 01 backpack, but the data range is impossible to do.
Before we consider the maximum value that can be obtained for a backpack that is loaded with V V in the former I I items, think about it, we consider the smallest volume of the first I items to be w W, so the problem can be solved.
AC Code
#include <iostream> #include <cstring> #include <algorithm> #define IO iOS:
: Sync_with_stdio (false); \ cin.tie (0); \ cout.tie (0);
using namespace Std;
typedef long Long LL;
const int MAXN = 1E5+10;
const int mod = 998244353;
const int inf = 0X3F3F3F3F;
LL n,b;
LL W[MAXN],V[MAXN];
LL dp[5100];
void Solve () {memset (dp,inf,sizeof (DP));
Dp[0] = 0;
for (int i=1, i<=n; i++) for (int j=5000; j>=v[i]; j--) dp[j] = min (dp[j],dp[j-v[i]]+w[i));
for (int i=5000; i>=0; i--) if (dp[i]<=b) {cout<<i<<endl;
Break
int main () {IO;
int T;
cin>>t;
while (t--) {cin>>n>>b;
for (int i=1; i<=n; i++) cin>>w[i]>>v[i];
Solve ();
return 0; }