-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathknapsack.cpp
More file actions
90 lines (75 loc) · 1.24 KB
/
knapsack.cpp
File metadata and controls
90 lines (75 loc) · 1.24 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Problema da Mochila
Huxley 790
Rodrigo Paes
*/
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 10000
#define MAX_M 100
int memo[MAX_N+1][MAX_M+1];
int p[MAX_N];
int w[MAX_N];
int c, n;
int dp_bottom_up()
{
for (int rc=0; rc <= c; ++rc)
{
for (int i=n; i >=0; --i)
{
if (rc==0 || i==n)
{
memo[i][rc] = 0;
}
else if (w[i] > rc)
{
memo[i][rc] = memo[i+1][rc];
}
else
{
memo[i][rc] = max( p[i] + memo[i+1][rc-w[i]], memo[i+1][rc] );
}
}
}
return memo[0][c];
}
int dp(int i, int rc)
{
if (memo[i][rc]!=-1) return memo[i][rc];
// printf("[%d][%d]\n", i, rc);
// parada
if (i == n) // já olhou todos os elementos
{
memo[i][rc] = 0;
}
else if ( rc == 0 ) // a mochila já acabou
{
memo[i][rc] = 0;
}
else if ( w[i] > rc ) // o item não cabe na mochila, ignora
{
memo[i][rc] = dp(i+1, rc);
}
else
{
// colocar ou não colocar
memo[i][rc] = max( p[i] + dp(i+1, rc-w[i]), dp(i+1, rc) );
}
return memo[i][rc];
}
int main()
{
memset(memo, -1, sizeof memo);
scanf("%d%d", &n, &c);
for (int i=0; i < n; ++i)
{
scanf("%d", &p[i]);
}
for (int i=0; i < n; ++i)
{
scanf("%d", &w[i]);
}
// printf("%d\n", dp(0,c));
printf("%d\n", dp_bottom_up());
return 0;
}