-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-knapsack.cpp
48 lines (47 loc) · 929 Bytes
/
01-knapsack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/** 01_knapsack
**/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin >> n >> m;
int profit[n];
int weight[n];
for(int i=0; i<n; i++)
{
cin >> profit[i];
}
for(int i=0; i<n; i++)
{
cin >> weight[i];
}
int v[n+1][m+1];
for(int i=0; i<=n; i++)
{
for(int w=0; w<=m; ++w)
{
if(i==0 || w==0)
{
v[i][w]=0;
}
else if(weight[i] <= w)
{
v[i][w]=max(v[i-1][w], v[i-1][w-weight[i]]+profit[i]);
}
else
{
v[i][w]=v[i-1][w];
}
}
}
cout << v[n][m] << '\n';
/* for(int i=0; i<=n; ++i)
{
for(int j=0; j<=m; ++j)
{
// cout << v[i][j] <<' ';
}
cout << '\n';
} */
}