Program
#include <stdio.h>
#include <conio.h>
#define MAX 50
int p[MAX], w[MAX], n;
int knapsack(int, int);
int max(int, int);
void main()
{
int m, i, optsoln;
printf("*********************************************************");
printf("\n*********************************************************");
printf("\n** WAP to implement 0/1 knapsack problem in C **");
printf("\n** Created by Sheetal Garg **");
printf("\n** Assistant Professor **");
printf("\n** Phone No:9467863365 **");
printf("\n*********************************************************");
printf("\n*********************************************************");
printf("\nEnter no. of objects: ");
scanf("%d", &n);
printf("\nEnter the weights:\n");
for (i = 1; i <= n; i++)
scanf("%d", &w[i]);
printf("\nEnter the profits:\n");
for (i = 1; i <= n; i++)
scanf("%d", &p[i]);
printf("\nEnter the knapsack capacity:");
scanf("%d", &m);
optsoln = knapsack(1, m);
printf("\nThe optimal solution is:%d", optsoln);
getch();
}
int knapsack(int i, int m)
{
if (i == n)
return (w[n] > m) ? 0 : p[n];
if (w[i] > m)
return knapsack(i + 1, m);
return max(knapsack(i + 1, m), knapsack(i + 1, m - w[i]) + p[i]);
}
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
Output 1
********************************************************* ********************************************************* ** WAP to implement 0/1 knapsack problem in C ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** ********************************************************* ********************************************************* Enter no. of objects: 4 Enter the weights: 20 10 15 25 Enter the profits: 500 300 200 100 Enter the knapsack capacity:50 The optimal solution is:1000