forked from GhadgeGauri/HactoberFest23
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 0/1 Knapsack problem in CPP.cpp
Hi @GhadgeGauri! #hactoberfest Closes GhadgeGauri#15 Thank you! Added the 0/1 Knapsack problem in CPP
- Loading branch information
1 parent
c5550a8
commit 2f5c7c3
Showing
1 changed file
with
47 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,47 @@ | ||
#include <iostream> | ||
#include <vector> | ||
|
||
using namespace std; | ||
|
||
// Structure to represent an item | ||
struct Item { | ||
int weight; | ||
int value; | ||
}; | ||
|
||
// Function to solve the 0/1 Knapsack problem using dynamic programming | ||
int knapsack(vector<Item>& items, int capacity) { | ||
int n = items.size(); | ||
// Create a 2D DP table to store the maximum value for each subproblem | ||
vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0)); | ||
|
||
// Fill the DP table using bottom-up approach | ||
for (int i = 1; i <= n; ++i) { | ||
for (int w = 1; w <= capacity; ++w) { | ||
// If the current item's weight is greater than the current capacity, | ||
// we can't include it in the knapsack | ||
if (items[i - 1].weight > w) { | ||
dp[i][w] = dp[i - 1][w]; | ||
} else { | ||
// Otherwise, we have two choices: include the item or exclude it | ||
// Take the maximum of these two choices | ||
dp[i][w] = max(dp[i - 1][w], items[i - 1].value + dp[i - 1][w - items[i - 1].weight]); | ||
} | ||
} | ||
} | ||
|
||
// The maximum value is stored in dp[n][capacity] | ||
return dp[n][capacity]; | ||
} | ||
|
||
int main() { | ||
// Example usage | ||
int capacity = 10; | ||
vector<Item> items = {{2, 6}, {2, 10}, {3, 12}, {5, 15}, {7, 22}}; | ||
|
||
int max_value = knapsack(items, capacity); | ||
|
||
cout << "Maximum value that can be obtained: " << max_value << endl; | ||
|
||
return 0; | ||
} |