Backpack 2
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
There are n items whose weight and value are respectively Wi and Vi. Now select items whose total amount is just W from these items, and find the maximum value of the sum of all solutions.
Input:
The input contains multiple sets of test cases, each of which starts with two-digit integers n and W (1<=n<=10000, 1<=W<=1000), followed by n lines, each with two-digit integers Wi, Vi (1<=Wi<=10000, 1<=Vi<=100).
Output:
The output is one row, the maximum value of the sum of the values across all scenarios. If there is no just filled condition, output "-1".
Sample Input:
3 4 1 2 2 5 2 1 3 4 1 2 2 5 5 1
Sample Output:
6 -1
Problem solving idea: This is a modified version of the 01 backpack. Combined with the question, if there is no situation where it is just filled to be -1, we can initialize all the elements of the dp array to -1, so that by directly outputting dp[W], we can know that the total amount selected from these items is exactly W, The state transition equation can only be used when the sum of its values also reaches the maximum and is not -1.
AC code:
1 #include<bits/stdc++.h> 2 using namespace std; 3 int w[ 10005 ],v[ 10005 ],dp[ 10005 ]; 4 int main() 5 { 6 int n,W; 7 while (cin> >n>> W){ 8 memset(dp,- 1 , sizeof (dp)); // all initialized to -1 9 dp[ 0 ]= 0 ; // default initialized to 0 10 for ( int i= 0;i<n;++ i) 11 cin>>w[i]>> v[i]; 12 for ( int i= 0 ;i<n;++ i){ 13 for ( int j=W;j >=w[i];-- j){ 14 if (dp[jw[i]]!=- 1 ) // If it is not -1, it can be compared and selected 15 dp[j]=max(dp[j ],dp[jw[i]]+ v[i]); 16 } 17 } 18 cout<<dp[W]<<endl; // Directly output the value when the total amount is W 19 } 20 return 0 ; 21}