-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
algorithms/dynamic-programming/knapsack-with-quantity-(no-recover).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |
6 changes: 6 additions & 0 deletions
6
algorithms/dynamic-programming/knapsack-with-quantity-(no-recover).tex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)$. |