Uploaded by keshav garg

Analysis and Design of Algorithms

advertisement
EXPERIMENT – 6
Aim: To implement 0/1 Knapsack Problem.
Software Used: Programiz Online Compiler
Experiment Conducted:
Algorithm of 0/1 Knapsack Problem:
1. Create a 2D array "dp" of size (n+1) x (W+1) where n is the number of
items and W is the maximum weight the knapsack can hold. Initialize all
values in dp to 0.
2. Iterate over each item from 1 to n:
For each item "i," iterate over each possible weight "w" from 1 to W:
If the weight of the current item is less than or equal to "w," calculate the
maximum value between adding the current item's value to dp[i-1][wweight[i]] (if you include the item) and dp[i-1][w] (if you exclude the
item), and store it in dp[i][w].
3. The final answer to the 0/1 Knapsack problem will be dp[n][W], which
represents the maximum value that can be obtained within the given
weight constraint.
Input:
#include <stdio.h>
#include <string.h>
int findMax(int n1, int n2){
if(n1>n2) {
return n1;
}
else {
return n2;
}
}
int knapsack(int W, int wt[], int val[], int n){
int K[n+1][W+1];
for(int i = 0; i<=n; i++) {
for(int w = 0; w<=W; w++) {
if(i == 0 || w == 0) {
K[i][w] = 0;
}
else if(wt[i-1] <= w) {
K[i][w] = findMax(val[i-1] + K[i-1][w-wt[i-1]], K[i-1]
[w]);
}
else {
K[i][w] = K[i-1][w];
}
}
}
return K[n][W];
}
int main(){
int val[5] = {10, 40, 30, 50};
int wt[5] = {5, 4, 6, 3};
int W = 10;
int len = sizeof val / sizeof val[0];
printf("Maximum Profit: %d", knapsack(W, wt, val, len));
return 0;
}
Output:
Conclusion: Hence, the experiment has been conducted successfully and the
results have been verified.
Download