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