0% found this document useful (0 votes)
11 views2 pages

0-1 Knapsack Unsing DP

The document presents a C program that implements the 0/1 Knapsack problem using dynamic programming. It prompts the user to input the number of objects, their profits, weights, and the capacity of the knapsack, then calculates and displays the maximum profit achievable. The program uses a 2D array to store intermediate results and employs a helper function to determine the maximum of two values.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
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
0% found this document useful (0 votes)
11 views2 pages

0-1 Knapsack Unsing DP

The document presents a C program that implements the 0/1 Knapsack problem using dynamic programming. It prompts the user to input the number of objects, their profits, weights, and the capacity of the knapsack, then calculates and displays the maximum profit achievable. The program uses a 2D array to store intermediate results and employs a helper function to determine the maximum of two values.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
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/ 2

0/1 Knapsack using dynamic:

#include <stdio.h>

int knapsack(int p[],int wt[],int n,int c);

int max(int a,int b);

void main() {

int n,profit[10],weight[10],capacity,i,result;

printf("enter number of objects");


scanf("%d",&n);

printf("enter profits");

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

{
scanf("%d",&profit[i]);

printf("enter weights");

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

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

printf("enter capacity");
scanf("%d",&capacity);

result=knapsack(profit,weight,n,capacity);

printf("Total profit is:%d",result);

int knapsack(int p[],int wt[],int n,int c)

int a[10][10];

int i,w;

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

for(w=0;w<=c;w++)
{
if(i==0||w==0)

a[i][w]=0;

else if(wt[i-1]>w)

a[i][w]=a[i-1][w];

}
else

a[i][w]=max(a[i-1][w],a[i-1][w-wt[i-1]]+p[i-1]);

}
}

return a[n][c];

int max(int a,int b)

return (a>b)?a:b;

}
Output:

enter number of objects4

enter profits3

5
6

enter weights2

enter capacity5

Total profit is:7

You might also like