ACM_01 Backpack 2

Backpack 4

Time Limit: 2000/1000ms (Java/Others)

Problem Description:

There are n items whose weight and value are Wi and Vi respectively. 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 begins with two-digit integers n and W; then there are n lines, each with two-digit integers Wi, Vi
in:
1<=n<=100
1<=W<=1000,000,000(10^9)
1<=Wi<=10,000,000(10^7)   
1 <= Vi <= 100。

Output:

The output is one row, the maximum value of the sum of the values ​​across all scenarios.

Sample Input:

4 5
2 3
1 2
3 4
2 2
4 10000000
2 3
2 2
3 3
1 2

Sample Output:

7
10 
Problem-solving ideas: Compared with the problem before the 01 backpack, only the size of the constraints is modified. The time complexity of solving this problem before is O(nW), but for this problem, the maximum W is 10^9, obviously Using the previous method will time out. However, it can be found that the range of value is relatively small compared to the weight, so this problem can be solved by changing the angle. In the previous method, dp[i] is to find the maximum value under which the current weight i does not exceed the total weight W, and this time dp[i][j] represents the total weight when the sum of the value of the first i items is j. Minimum value (a sufficiently large INF when not present).
State transition equation: dp[i+1][j]=min(dp[i][j],dp[i][jv[i]]+w[i]).
AC code:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define MAX_n 100
 4 #define MAX_v 100
 5 const int INF = 0x3f3f3f3f;
 6 int w[MAX_n+1],v[MAX_n+1],dp[MAX_n+1][MAX_n*MAX_v+1];
 7 int main()
 8 {
 9     int n,W;
10     while(cin>>n>>W){
11         fill(dp[0],dp[0]+MAX_n*MAX_v+1,INF);
12         dp[0][0]=0;
13         for(int i=0;i<n;++i)
14             cin>>w[i]>>v[i];
15         for(int i=0;i<n;++i){
16             for(int j=0;j<=MAX_n*MAX_v;++j){
17                 if(j<v[i])dp[i+1][j]=dp[i][j];
18                 else dp[i+1][j]=min(dp[i][j],dp[i][j-v[i]]+w[i]);
19             }
20         }
21         int res=0;
22         for(int i=0;i<=MAX_n*MAX_v;++i)
23             if(dp[n][i]<=W)res=i;
24         cout<<res<<endl;
25     }
26     return 0;
27 }

 

Guess you like

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