|
| 1 | +/* |
| 2 | + * Algorithm: 0/1 Knapsack Problem |
| 3 | + * Language: C++ |
| 4 | + * Description: Given weights and values of n items, determine the maximum value |
| 5 | + * that can be put in a knapsack of capacity W. Each item can be |
| 6 | + * included at most once (0/1 property). |
| 7 | + * Time Complexity: O(n * W) where n = number of items, W = knapsack capacity |
| 8 | + * Space Complexity: O(n * W) |
| 9 | + */ |
| 10 | + |
| 11 | +#include <iostream> |
| 12 | +#include <vector> |
| 13 | +#include <algorithm> |
| 14 | + |
| 15 | +using namespace std; |
| 16 | + |
| 17 | +/** |
| 18 | + * Function to solve 0/1 Knapsack problem using DP |
| 19 | + * |
| 20 | + * @param weights vector of item weights |
| 21 | + * @param values vector of item values |
| 22 | + * @param capacity maximum capacity of the knapsack |
| 23 | + * @return maximum total value that fits in the knapsack |
| 24 | + */ |
| 25 | +int knapsack01(const vector<int> &weights, const vector<int> &values, int capacity) { |
| 26 | + int n = weights.size(); |
| 27 | + |
| 28 | + // DP table initialization (n+1 x capacity+1) |
| 29 | + vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0)); |
| 30 | + |
| 31 | + // Fill DP table |
| 32 | + for (int i = 1; i <= n; i++) { |
| 33 | + for (int w = 0; w <= capacity; w++) { |
| 34 | + if (weights[i - 1] <= w) { |
| 35 | + // Take maximum of including or excluding current item |
| 36 | + dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]); |
| 37 | + } else { |
| 38 | + // Cannot include current item |
| 39 | + dp[i][w] = dp[i - 1][w]; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return dp[n][capacity]; // Maximum value achievable |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * Test function for 0/1 Knapsack implementation |
| 49 | + */ |
| 50 | +void testKnapsack() { |
| 51 | + vector<pair<vector<int>, vector<int>>> testCases = { |
| 52 | + {{1, 2, 3, 8}, {10, 20, 30, 90}}, // Items 1-4 |
| 53 | + {{3, 2, 1}, {50, 40, 60}}, // Smaller knapsack |
| 54 | + {{5, 4, 6, 3}, {10, 40, 30, 50}} // Random test |
| 55 | + }; |
| 56 | + vector<int> capacities = {10, 5, 10}; |
| 57 | + |
| 58 | + for (int i = 0; i < testCases.size(); i++) { |
| 59 | + int maxVal = knapsack01(testCases[i].first, testCases[i].second, capacities[i]); |
| 60 | + cout << "Test Case " << i + 1 << ":\n"; |
| 61 | + cout << "Weights: "; |
| 62 | + for (auto w : testCases[i].first) cout << w << " "; |
| 63 | + cout << "\nValues: "; |
| 64 | + for (auto v : testCases[i].second) cout << v << " "; |
| 65 | + cout << "\nKnapsack Capacity: " << capacities[i] << "\n"; |
| 66 | + cout << "Maximum Value: " << maxVal << "\n\n"; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +int main() { |
| 71 | + cout << "Testing 0/1 Knapsack Problem Implementation\n\n"; |
| 72 | + testKnapsack(); |
| 73 | + return 0; |
| 74 | +} |
0 commit comments