0% found this document useful (0 votes)
1 views3 pages

PROGRAM 6 Knapsack Dynamic

The document provides a C/C++ program to solve the 0/1 Knapsack problem using dynamic programming. It includes functions for calculating maximum profit and tracing the items included in the knapsack based on user input for weights, profits, and capacity. The program outputs the items included in the knapsack along with the total profit achieved.

Uploaded by

apoorvanayak07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views3 pages

PROGRAM 6 Knapsack Dynamic

The document provides a C/C++ program to solve the 0/1 Knapsack problem using dynamic programming. It includes functions for calculating maximum profit and tracing the items included in the knapsack based on user input for weights, profits, and capacity. The program outputs the items included in the knapsack along with the total profit achieved.

Uploaded by

apoorvanayak07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

PROGRAM 6

Design and implement C/C++ Program to solve 0/1 Knapsack problem using

Dynamic Programming method.

#include <stdio.h>

int w[10], p[10], v[10][10], n, i, j, cap, x[10] = {0};

int max(int i, int j) {

return ((i > j) ? i : j);

int knap(int i, int j) {

int value;

if (v[i][j] < 0) {

if (j < w[i])

value = knap(i - 1, j);

else

value = max(knap(i - 1, j), p[i] + knap(i - 1, j - w[i]));

v[i][j] = value;

return (v[i][j]);

void main() {

int profit, count = 0;

// Input number of items

printf("\nEnter the number of elements\n");

scanf("%d", &n);

// Input the profit and weights for each item

printf("Enter the profit and weights of the elements\n");

for (i = 1; i <= n; i++) {

printf("For item no %d\n", i);

scanf("%d%d", &p[i], &w[i]);

// Input the knapsack capacity


printf("\nEnter the capacity \n");

scanf("%d", &cap);

// Initialize the DP table v[][]

for (i = 0; i <= n; i++) {

for (j = 0; j <= cap; j++) {

if ((i == 0) || (j == 0))

v[i][j] = 0;

else

v[i][j] = -1;

// Calculate the maximum profit

profit = knap(n, cap);

// Trace the items included in the knapsack

i = n;

j = cap;

while (j != 0 && i != 0) {

if (v[i][j] != v[i - 1][j]) {

x[i] = 1; // Item i is included

j = j - w[i];

i--;

// Output the items that are included

printf("Items included are\n");

printf("Sl.no\tweight\tprofit\n");

for (i = 1; i <= n; i++) {

if (x[i]) {

printf("%d\t%d\t%d\n", ++count, w[i], p[i]);

}
// Output the total profit

printf("Total profit = %d\n", profit);

You might also like