Aizu - DPL_1_B 0-1 Knapsack Problem【基础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
 1 #include<iostream>
 2 using namespace std;
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cstdlib>
 6 typedef long long ll;
 7 ll f[30000];
 8 ll a[300];
 9 ll w[300];
10 ll ans = 0;
11 int main(){
12     int n,m;
13     scanf("%d%d",&n,&m);
14     for(int i=0;i<n;i++)
15         scanf("%lld%lld",&a[i],&w[i]);
16     memset(f,0,sizeof(f));
17     for(int i=0;i<n;i++){
18         for(int j=m;j>=w[i];j--){
19             if(f[j-w[i]]+a[i]>f[j])
20                 f[j] = f[j-w[i]] + a[i];
21             if(f[j]<0x3f3f3f3f)
22                 ans = max(ans,f[j]);
23         }
24     }
25     cout<<ans<<endl;
26     return 0;
27 }

 

posted @ 2018-04-02 20:05  晓风微微  阅读(275)  评论(0编辑  收藏  举报