ACM_01 Backpack

Backpack 1

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 does not exceed W from these items, and find the maximum value of the sum of all the 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.

Sample Input:

3 4
1 2
2 5
3 7

Sample Output:

9 
Problem-solving ideas: simple 01 backpack, one-dimensional array implementation.
AC code:
1 #include<bits/stdc++.h>
 2  using  namespace std;
 3  int v[ 10005 ],w[ 10005 ],dp[ 10005 ]; // The dp array always records the maximum value of the current volume 
4  int main()
 5  {
 6      int n,W;
 7      while (cin>>n>> W){
 8          for ( int i= 0 ;i<n;i++ )
 9              cin>>w[i]>> v[i];
 10          memset( dp, 0 , sizeof (dp));
 11         for ( int i= 0 ;i<n;++i){     // Number 
12              for ( int j=W;j>=w[i];--j) // 01 Backpack 
13                  dp[j]= max(dp[j],dp[jw[i]]+v[i]); // Compare the value after placing the i object with the value before not placing it, and record the larger value 
14          }
 15          cout<<dp[ W]<<endl; // Output the maximum value of the total volume 
16      }
 17      return  0 ;
 18 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382302&siteId=291194637