0% found this document useful (0 votes)
4 views

Program7 Greedy Knapsack

The document implements a greedy approximation algorithm in C/C++ to solve the continuous knapsack problem. It defines variables, takes user input for number of objects and knapsack capacity, calculates profit to weight ratios, sorts them in descending order, and fills the knapsack greedily by taking fractional amounts if the object weight exceeds remaining capacity.

Uploaded by

Akaash MS BLR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Program7 Greedy Knapsack

The document implements a greedy approximation algorithm in C/C++ to solve the continuous knapsack problem. It defines variables, takes user input for number of objects and knapsack capacity, calculates profit to weight ratios, sorts them in descending order, and fills the knapsack greedily by taking fractional amounts if the object weight exceeds remaining capacity.

Uploaded by

Akaash MS BLR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

7.

Design and implement C/C++ problem to solve discrete knapsack and


continuous knapsack problems using greedy approximation method.
//Continuous Knapsack

#include<stdio.h>

#define MAX 50

int p[MAX],w[MAX];

float x[MAX];

int n,m,i,j;

void greedyknapsack(int n, int w[], int p[], int m);

int main()

//clrscr();

printf("enter the number of objects");

scanf("%d",&n);

printf("enter the knapsack capacity\n");

scanf("%d",&m);

printf("enter the profit of each object\n");

for(i=0;i<n;i++)

scanf("%d",&p[i]);

printf("enter the weight of each object\n");

for(i=0;i<n;i++)

scanf("%d",&w[i]);

greedyknapsack(n,w,p,m);

return 0;

getch();

void greedyknapsack(int n, int w[], int p[], int m)

double ratio[MAX],temp2;

int currentweight=0;
double maxprofit=0;

for(i=0; i<n; i++)

ratio[i]=(double)p[i]/w[i];

for(i=0; i<n-1; i++)

for(j=i+1; j<n;j++)

if(ratio[i]<ratio[j])

double temp=ratio[i];

ratio[i]=ratio[j];

ratio[j]=temp;

temp2=w[i];

w[i]=w[j];

w[j]=temp2;

temp2=p[i];

p[i]=p[j];

p[j]=temp2;

for(i=0;i<n;i++)

if(currentweight+w[i]<=m)

x[i]=1;

currentweight+=w[i];

maxprofit+=p[i];

}
else //Remove else part for Discrete Knapsack

x[i]=(m-currentweight)/(double)w[i];

maxprofit+=x[i]*p[i];

break;

printf("optimal solution for greedy method:%lf\n",maxprofit);

printf("the solution vector for greedy method:");

for(i=0;i<n;i++)

printf("%f\t",x[i]);

You might also like