We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1
EXPERIMENT-9 if (i == 0 || w == 0) } OUTPUT:
dp[i][w] = 0; Enter number of items: 3
Demonstrate a program to solve 0/1Knapsack problem Using else if (weights[i - 1] <= w) int main() { Enter the profits and weights of each item: Dynamic Programming. dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]); int n, W; Item 1 - profit: 1 Aim: To demonstrate 0/1Knapsack problem Using Dynamic Programming. else printf("Enter number of items: "); Item 1 - Weight: 2 Description: We are given N items where each item has some weight and dp[i][w] = dp[i - 1][w]; scanf("%d", &n); profit associated with it. We are also given a bag with capacity m, [i.e., the bag Item 2 - profit: 2 can hold at most m weight in it]. The target is to put the items into the bag } Item 2 - Weight: 3 without exceeding the limit of the Knapsack , Such that the sum of profits } int values[n], weights[n]; Item 3 - profit: 5 associated with them is the maximum possible. The constraint here is we can either put an item completely into the bag or cannot put it at all but It is not printf("Enter the profits and weights of each item:\n"); Item 3 - Weight: 4 possible to put a part of an item into the bag. This is a 0/1 knapsack problem in // Store the result (maximum profit) for (int i = 0; i < n; i++) { Enter the maximum weight capacity of the knapsack: 6 which either we pick the item completely or leave it completely. Hence, in case of 0/1 Knapsack, the value of xi can be either 0 or 1. int maxValue = dp[n][W]; printf("Item %d - profit: ", i + 1); Items included in the knapsack: scanf("%d", &values[i]); Item 3 (Profit: 5, Weight: 4) Program: // Find the items included in the knapsack for the optimal solution printf("Item %d - Weight: ", i + 1); Item 1 (Profit: 1, Weight: 2) #include <stdio.h> int w = W; scanf("%d", &weights[i]); Maximum profit that can be obtained in the knapsack is: 6 printf("Items included in the knapsack:\n"); }
// Function to get the maximum of two values for (int i = n; i > 0 && maxValue > 0; i--) {
int max(int a, int b) { // If the value comes from the item inclusion printf("Enter the maximum weight capacity of the knapsack: ");
return (a > b) ? a : b; if (maxValue != dp[i - 1][w]) { scanf("%d", &W);
1]); int maxValue = knapsack(W, weights, values, n); // Subtract the value and weight of the included item // Function to solve the 0/1 Knapsack problem and track the items included printf("Maximum profit that can be obtained in the knapsack is: %d\n", maxValue -= values[i - 1]; maxValue); int knapsack(int W, int weights[], int values[], int n) { w -= weights[i - 1]; int dp[n+1][W+1]; } return 0; } } // Building the table dp[][] in a bottom-up manner for (int i = 0; i <= n; i++) { // Return the maximum value obtained for (int w = 0; w <= W; w++) { return dp[n][W];