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

AIM Program To Implement 0/1 Knapsack Problem

The document describes a C program to solve the 0/1 knapsack problem. The program takes item weights and values as input, along with the maximum capacity of the knapsack. It uses a 2D array kp to store the optimal values for including items in the knapsack. The knapsack() function fills this array, while find_knapsack() traces back through the array to output the items selected for the knapsack.

Uploaded by

Atom Gaming
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)
24 views2 pages

AIM Program To Implement 0/1 Knapsack Problem

The document describes a C program to solve the 0/1 knapsack problem. The program takes item weights and values as input, along with the maximum capacity of the knapsack. It uses a 2D array kp to store the optimal values for including items in the knapsack. The knapsack() function fills this array, while find_knapsack() traces back through the array to output the items selected for the knapsack.

Uploaded by

Atom Gaming
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/ 2

AIM:-PROGRAM TO IMPLEMENT 0/1

KNAPSACK PROBLEM.

#include<stdio.h>
#include<conio.h>

void knapsack(int [],int [],int,int);


void find_knapsack(int[],int,int);
int kp[100][100];

void main(){
int i,m,n,p[100],w[100];
clrscr();
printf("Enter number of items: ");
scanf("%d",&n);
printf("\nEnter the values of P: ");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("\nEnter the values of w: ");
for(i=0;i<n;i++)
scanf("%d",&w[i]);
printf("\nEnter maximum capacity: ");
scanf("%d",&m);
knapsack(p,w,m,n);
find_knapsack(w,m,n);
getch();
}

void knapsack(int P[],int W[],int M,int n){


int i,j;
for(i=1;i<=n;i++)
kp[i][0]=0;
for(j=0;j<=M;j++)
kp[0][j]=0;
for(i=1;i<=n;i++){
for(j=1;j<=M;j++){
if(W[i-1]>j)
kp[i][j]=kp[i-1][j];
else if(kp[i-1][j]>(kp[i-1][j-W[i-1]]+P[i-1]))
kp[i][j]=kp[i-1][j];
else
kp[i][j]=kp[i-1][j-W[i-1]]+P[i-1];
}
}
}

void find_knapsack(int W[],int M,int n){


int i=n,j=M;
printf("\nItem in Knapsack: ");
while(i>0 && j>0){
if(kp[i][j]!=kp[i-1][j]){
printf("w%d=%d ",i,W[i-1]);
i=i-1;
j=j-W[i-1];
}
else
i=i-1;
}
}

OUTPUT:

You might also like