Search
 
SCRIPT & CODE EXAMPLE
 

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();
}
Comment

PREVIOUS NEXT
Code Example
C :: how to ban websites on mac 
C :: A binary tree whose every node has either zero or two children is called 
C :: unity set transform position code 
C :: c bit access union 
C :: c integer to string 
C :: print bool c 
C :: c assign pointer to struct 
C :: tkinter create_line 
C :: scanf string in c 
C :: typedef pointer 
C :: insertion sort c 
C :: downgrade chrome to previous stable version in linux 
C :: c program to print the multiplication table 
C :: gcc option to show rules of makefile 
C :: c style string 
C :: c fopen 
C :: c read file 
C :: how to reset all values of 2d vector to 0 
C :: simple bootstrap form example 
C :: unable to locate package dos2unix 
C :: how to get the lowest number on a array in c 
C :: mongo connect db 
C :: #0000ff 
C :: binary tree count number of leaves in c 
C :: Happy birthday in C 
C :: threads in c 
C :: %= in c 
C :: how to read and write to fiel n c 
C :: fungetc 
C :: C/c drop mime 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =