zoukankan      html  css  js  c++  java
  • 问题 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;
    }


  • 相关阅读:
    Nginx服务器中配置非80端口的端口转发方法详解
    索引的优缺点
    redis cluster搭建
    linux 无需主机密码传输文件
    linux buffer/cache手动释放
    常用的Percona-Toolkit工具
    mysql 存储过程批量删除表
    redis(方法通用)开机自启动
    mysql 查看表的分区信息
    redis 内存分析
  • 原文地址:https://www.cnblogs.com/acerkoo/p/9490315.html
Copyright © 2011-2022 走看看