Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

0/1 knapsack problem in c

#include<stdio.h>
#include<conio.h>
void main()
{
printf("
Enter the no of elements: "); int noe; scanf("%d",&noe);
int p[noe], w[noe], r[noe], pw[noe], i, I, sack, np=0, cnoe=noe;
printf("
Enter the profits: "); for(i=0;i<noe;i++) scanf("%d",&p[i]);
printf("
Enter the weights: "); for(i=0;i<noe;i++) scanf("%d",&w[i]);
printf("
Enter the size of the sack: "); scanf("%d",&sack);
for(i=0;i<noe;i++) r[i] = 1; for(i=0;i<noe;i++) pw[i] = p[i]/w[i];
while(sack>0 && cnoe>0)
{
  int v=-1;
  for(i=0;i<noe;i++){if(v<=pw[i] && r[i]==1){I=i; v=pw[i];}}
  r[I] = 0; cnoe--;
  if(w[I]<sack){sack=sack-w[I];np = np + p[I];}
  else{np = np + pw[I]*(sack);sack=0;}
  printf("
 No=%d, sack=%d, profit=%d", I+1, sack, np);
}
printf("
Net profit from the sack: %d ", np); getch();
}
 
PREVIOUS NEXT
Tagged: #knapsack #problem
ADD COMMENT
Topic
Name
2+7 =