Skip to content

Commit

Permalink
✨ adds knapsack with quantity
Browse files Browse the repository at this point in the history
  • Loading branch information
iagorrr committed Mar 13, 2024
1 parent 7c11b9b commit 41c26bf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
ll knapsack(const vi &weight, const vll &value, const vi &qtd, int maxCost) {
vi costs;
vll values;
for (int i = 0; i < len(weight); i++) {
ll q = qtd[i];
for (ll x = 1; x <= q; q -= x, x <<= 1) {
costs.eb(x * weight[i]);
values.eb(x * value[i]);
}
if (q) {
costs.eb(q * weight[i]);
values.eb(q * value[i]);
}
}

vll dp(maxCost + 1);
for (int i = 0; i < len(values); i++) {
for (int j = maxCost; j > 0; j--) {
if (j >= costs[i]) dp[j] = max(dp[j], values[i] + dp[j - costs[i]]);
}
}
return dp[maxCost];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
\subsection{Knapsack with quantity (no recover)}

finds the maximum score you can achieve, given that you have $n$ items, each item has a $cost$, a $point$ and a $quantity$, you can spent at most $maxcost$ and buy each item the maximum quantity it has.

time: $O(n \cdot maxcost \cdot \log{maxqtd})$
memory: $O(maxcost)$.

0 comments on commit 41c26bf

Please sign in to comment.