-
Notifications
You must be signed in to change notification settings - Fork 25
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
1 parent
fac919c
commit acd0cca
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
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,39 @@ | ||
#ifndef KNAPSACK_H | ||
#define KNAPSACK_H | ||
|
||
#ifdef __cplusplus | ||
#include <iostream> | ||
#include <vector> | ||
#include <utility> | ||
#endif | ||
|
||
/** | ||
* @brief knapsack 0/1 function | ||
* @param v the passed vector | ||
* @param capacity the capacity of the knapsack | ||
* @return int: the maximum value you can collect with a knapsack of the passed capacity | ||
*/ | ||
int knapsack(std::vector<std::pair<int, int> > &v, int capacity) { | ||
if(capacity == 0) { | ||
return 0; | ||
} | ||
|
||
int n = int(v.size()); | ||
std::vector<std::vector<int > > dp(n + 1, std::vector<int>(capacity + 1)); | ||
|
||
for(int i = 1; i<=n; i++) { | ||
for(int j = 0; j<=capacity; j++) { | ||
dp[i][j] = dp[i - 1][j]; | ||
if(i == 0 || j == 0) { | ||
dp[i][j] = 0; | ||
} | ||
else if(v[i - 1].first <= j) { | ||
dp[i][j] = std::max(dp[i - 1][j], v[i - 1].second + dp[i - 1][j - v[i - 1].first]); | ||
} | ||
} | ||
} | ||
|
||
return dp[n][capacity]; | ||
} | ||
|
||
#endif |
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,12 @@ | ||
#include "../../../third_party/catch.hpp" | ||
#include "../../../src/algorithms/dynamic_programming/knapsack.h" | ||
|
||
TEST_CASE("Testing knapsack 0/1 [1]") { | ||
std::vector<std::pair<int, int> > v = {{10, 60}, {20, 100}, {30, 120}}; | ||
|
||
REQUIRE(knapsack(v, 50) == 220); | ||
v.clear(); | ||
v = {{5, 40}, {3, 20}, {6, 10}, {3, 30}}; | ||
|
||
REQUIRE(knapsack(v, 10) == 70); | ||
} |