问题 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值