Daa Mad Worksheet7 CPP NEMESIS
Daa Mad Worksheet7 CPP NEMESIS
Experiment 7
1. Aim:
Develop a program and analyze complexity to implement 0-1 Knapsack
using Dynamic Programming.
2. Objective
To implement 0-1 Knapsack using Dynamic Programming.
3. Algorithm
o Initialize a 2D table for storing results.
o For each item, update the table with the maximum profit for each
weight.
o Consider both including and excluding the item.
o Repeat for all items and capacities.
o The final cell in the table contains the maximum profit.
4. Implemetation/Code
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000;
int knapsack(int W, int wt[], int profit[], int n) {
int dp[MAXN + 1][MAXN + 1] = {0};
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if (wt[i - 1] <= w)
dp[i][w] = max(dp[i - 1][w], profit[i - 1] + dp[i - 1][w - wt[i - 1]]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
int main() {
int n, W;
cout << "ENTER NUMBER OF ITEMS AND CAPACITY: ";
cin >> n >> W;
if (n <= 0 || W <= 0) {
cout << "Number of items and capacity must be positive." << endl;
return 1;
}
if (n > MAXN || W > MAXN) {
cout << "Number of items or capacity exceeds maximum allowed size." << endl;
return 1;
}
int profit[MAXN], wt[MAXN];
cout << "ENTER PROFITS AND WEIGHTS: ";
for (int i = 0; i < n; ++i) {
cin >> profit[i] >> wt[i];
}
cout << "MAXIMUM KNAPSACK VALUE: " << knapsack(W, wt, profit, n) <<
endl;
return 0;
}
Output
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
7. Learning Outcomes:-