问题 J: Simple Knapsack

问题 J: Simple Knapsack

时间限制: 1 Sec  内存限制: 128 MB
提交: 65  解决: 24
[提交][状态][讨论版][命题人:admin]

题目描述

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,…,N, w1≤wi≤w1+3.
1≤vi≤107
W, each wi and vi are integers.

输入

Input is given from Standard Input in the following format:
N W
w1 v1
w2 v2
:
wN vN

输出

Print the maximum possible total value of the selected items.

样例输入

4 6
2 1
3 4
4 10
3 4

样例输出

11

提示

The first and third items should be selected.

 

题意: 背包大小 1e9 范围内的01背包。

思路:

每个物品的w 只有四种状态(w[1] <= w[i] <= w[1] +3),那么可以 将每个 w[i] 减小 w[1]  ,然后维护到前 i 个 数取 j 个 数时的01背包。

 

代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=110;
ll dp[maxn][maxn*3];
ll n,s,w[maxn],v[maxn];
 
int main(){
    cin>>n>>s;
    for (int i=1; i<=n ;i++)
        cin>>w[i]>>v[i];
    w[0]=w[1]-1;
    ll sum=0;
    for (int i=1; i<=n ;i++) w[i]-=w[0],sum+=w[i];
    ll ans=0;
 
    for (int i=1; i<=n ;i++){
        for (int j=i;j >=1;j--){
            for (int k=sum;k>=w[i];k--){
                dp[j][k]=max(dp[j][k],dp[j-1][k-w[i]]+v[i]);
                if(1ll*j*w[0]+k<=s) ans=max(dp[j][k],ans);
            }
        }
    }
 
    cout<<ans<<endl;
    return 0;
}


posted @ 2018-06-09 22:04  Acerkoo  阅读(155)  评论(0编辑  收藏  举报