Simple Knapsack(AtCoder-2556)

Problem Description

You have N items and a bag of strength W. The i-th item has a weight of wi and a value of vi.

You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

  • 1≤N≤100
  • 1≤W≤109
  • 1≤wi≤109
  • For each i=2,3,…,Nw1≤wiw1+3.
  • 1≤vi≤107
  • W, each wi and vi are integers.

Input

Input is given from Standard Input in the following format:

N W
w1 v1
w2 v2
:
wN vN

Output

Print the maximum possible total value of the selected items.

Example

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11
The first and third items should be selected.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

13
The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400
You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0
You can take nothing.

题意: n 件物品,背包容量为 w,第 i 件物品重量为 wi,价值为 vi,求最大价值

思路:01背包

由于容量 W 最大到 1E9,超出数组范围,因此需要优化

每件物品重量都在 [w1,w1+3] 范围内,因此可以将 w1 提出来, 原来的状态 dp[i][j] 表示前 i 个物品重量为 j 时的最大价值,将 w1 提出来后将 dp[i][j] 改为 dp[i][j][k],表示 前 i 个物品占 k*w1+j 质量时的最大价值,其中 k 表示放进去 k 个物品,j 表示多出来的质量,且由于将 w1 提出来,多出的质量 j 不会超过 300

Source Program

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 500+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
LL w[N],v[N];
LL dp[N][N][N];
int main(){
    LL n,W;
    scanf("%lld%lld",&n,&W);
    for(int i=1;i<=n;i++)
        scanf("%lld%lld",&w[i],&v[i]);

    LL w1=w[1];
    for(int i=1;i<=n;i++)
        w[i]-=w1;
    for(int i=1;i<=n;i++){
        for(int j=0;j<=n;j++){
            for(int k=1;k<=n;k++){
                if(j>=w[i]){
                    dp[i][j][k]=max(dp[i-1][j][k],dp[i-1][j-w[i]][k-1]+v[i]);
                }
                else{
                    dp[i][j][k]=dp[i-1][j][k];
                }
            }
        }
    }

    LL res=0;
    for(int j=0;j<=300;j++){
        for(int k=0;k<=n;k++){
            if(k*w1+j<=W){
                res=max(res,dp[n][j][k]);
            }
        }
    }
    printf("%lld\n",res);

    return 0;
}

 

你可能感兴趣的:(#,AtCoder,#,动态规划——背包问题)