39 Daa4
39 Daa4
Assignment No: 04
Aim: Write a program to solve a 0-1 Knapsack problem using dynamic programming
or branch and bound strategy.
Code:
#include <bits/stdc++.h>
#include <chrono>
int n = values.size();
// dp[i][w] represents the maximum value that can be obtained with i items and a knapsack
of capacity w.
if (i == 0 || w == 0) {
dp[i][w] = 0;
} else {
}}
// Trace the solution to get the included items.
int i = n, w = capacity;
w -= weights[i - 1];
i--;
// The value in the bottom-right corner of the table represents the maximum value that can
be obtained.
return dp[n][capacity];
int main() {
int n, capacity;
cin >> n;
vector<int> values(n);
vector<int> weights(n);
}
cout << "Enter the knapsack capacity: ";
cout << "\nSolution vector (1 for included, 0 for not included): ";
cout << "\nTime taken: " << duration.count() << " milliseconds" << endl;
return 0;
Output:
Maximum value: 40