Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

❖ Knapsack Problem

#include <stdio.h>
static void swap(int x[],int j){
int temp=0;
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
}
int main() {

float ftemp=0;
int n,cap;
printf("Enter no of elements: ");
scanf("%d",&n);
printf("Enter Capacity: ");
scanf("%d",&cap);

int p[n],w[n],o[n],s[n];
float pw[n];

printf("Enter Profit & Weight: ");


for(int i=0;i<n;i++){
scanf("%d",&p[i]);
scanf("%d",&w[i]);
o[i]=i;
pw[i]=(float) p[i]/(float) w[i];
}
printf("\n");

for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(pw[j]<pw[j+1]){
ftemp=pw[j];
pw[j]=pw[j+1];
pw[j+1]=ftemp;
swap(p,j);
swap(w,j);
swap(o,j);
}
}
}

printf("objects\tprofit\tweight\tshare\t\tProfit\n");

float share=1,profit=0;
for(int i=0;i<n;i++){
share=1;
printf("%d\t\t",o[i]+1);
printf("%d\t\t",p[i]);
printf("%d\t\t",w[i]);
if(w[i]<cap){
cap=cap-w[i];
s[i]=1;
}
else {
share=(float) cap/(float) w[i];
s[i]=share;
cap=0;
}
printf("%f\t",share);
printf("%f\t",share*p[i]);
profit=(p[i]*share)+profit;
printf("\n");
}
printf("Total Profit %f",profit);

return 0;
}

➢ Output

You might also like