Knapsack Problem(完全背包模板)

滴答滴答---题目链接 

You have N kinds of items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

  • The total value of the items is as large as possible.
  • The items have combined weight at most W, that is capacity of the knapsack.
  • You can select as many items as possible into a knapsack for each kind.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

  • 1 ≤ N ≤ 100
  • 1 ≤ vi ≤ 1000
  • 1 ≤ wi ≤ 1000
  • 1 ≤ W ≤ 10000

Sample Input 1

4 8
4 2
5 2
2 1
8 3

Sample Output 1

21

 

Sample Input 2

2 20
5 9
4 10

Sample Output 2

10

 

Sample Input 3

3 9
2 1
3 1
5 2

Sample Output 3

27

 0-1背包问题描述:一个正在抢劫商店的小偷发现了n个商品,第i个商品价值 vi 美元,重 wi 磅,vi 和 wi 都是整数。这个小偷希望拿走价值尽量高的商品,但他的背包最多能容纳 S 磅重的商品,S 是一个整数,那么他应该如何拿才能使得背包中的商品价值之和最大。

  0-1背包问题的特点在于这类问题只能做出二元选择,比如上面描述的问题中每个商品不可拆分,小偷要么把它拿走,要么把它留下;不能拿走商品的一部分。所以有可能最后结果小偷的背包还有多余的空间,但却不能再多放商店的商品了。这也是使用动态规划求解方法的原因。

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int inf=0x3f3f3f;
int dp[10010];
int a[10100],w[10010];
int main()
{
    memset(dp,0,sizeof(dp));
    int m,n;
    cin>>n>>m;
    for(int i=1; i<=n; i++)
        cin>>a[i]>>w[i];
    for(int i=1; i<=n; i++)
        for(int j=w[i]; j<=m; j++)
            dp[j]=max(dp[j],dp[j-w[i]]+a[i]);
    printf("%d\n",dp[m]);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值