1. 程式人生 > >AOJ 0-1 Knapsack Problem 01揹包 dp

AOJ 0-1 Knapsack Problem 01揹包 dp

You have N 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.

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 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9

 遞推關係:

dp[i][j]=max(dp[i-1][j],dp[i-1][j-b[i].w]+b[i].v);

注意要做好初始化。。。

程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=105;
const int maxw=10005;
int n,w;
struct bag
{
    int v;
    int w;
};
bag b[maxn];
int dp[maxn][maxw];
int main()
{
    scanf("%d%d",&n,&w);
    for (int i=1;i<=n;i++)
        scanf("%d%d",&b[i].v,&b[i].w);
    for (int i=0;i<=w;i++)
        dp[0][i]=0;
    for (int i=1;i<=n;i++)
        dp[i][0]=0;
    for (int i=1;i<=n;i++)
    {
        for (int j=1;j<=w;j++)
        {
            dp[i][j]=dp[i-1][j];
            if(j<b[i].w)
                continue;
            dp[i][j]=max(dp[i-1][j],dp[i-1][j-b[i].w]+b[i].v);
        }
    }
    printf("%d\n",dp[n][w]);
    return 0;
}