0% found this document useful (0 votes)
19 views3 pages

7.knapsack Using Greedy Method

The document presents a C++ implementation of the Knapsack problem using a greedy method. It defines a function to calculate the maximum profit based on the weights and profits of items while considering the capacity of the knapsack. The program prompts the user for input and outputs the result vector and maximum profit achieved.

Uploaded by

ponni.world009
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)
19 views3 pages

7.knapsack Using Greedy Method

The document presents a C++ implementation of the Knapsack problem using a greedy method. It defines a function to calculate the maximum profit based on the weights and profits of items while considering the capacity of the knapsack. The program prompts the user for input and outputs the result vector and maximum profit achieved.

Uploaded by

ponni.world009
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/ 3

7.

Knapsack problem using greedy method

#include<iostream.h>

#include<conio.h>

void knapsack(float n, float weight[], float profit[],float capacity)

float x[20],tp=0;

float i,j,u;

u=capacity;

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

x[i]=0.0;

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

if(weight[i]>u)

break;

else

x[i]=1.0;

tp=tp+profit[i];

u=u-weight[i];

if(i<n)

x[i]=u/weight[i];

tp=tp+(x[i]*profit[i]);

cout<<"\n The result vector is:";


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

cout.precision(4);

cout<<x[i];

cout<<"\n maximum profit is:"<<tp;

getch();

void main()

clrscr();

float weight[20],profit[20],capacity;

float num,i,j;

float ratio[20],temp;

cout<<"\n Enter the number of object:";

cin>>num;

cout<<"\n Enter the weight & profit of each object:";

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

cin>>weight[i]>>profit[i];

cout<<"\n Enter the capacity of knapsack:";

cin>>capacity;

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

ratio[i]=profit[i]/weight[i];

}
for(i=0;i<num;i++)

for(j=j+1;j<num;j++)

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

temp=ratio[j];

ratio[j]=ratio[i];

ratio[i]=temp;

temp=weight[j];

weight[j]=weight[i];

weight[i]=temp;

temp=profit[j];

profit[j]=profit[i];

profit[i]=temp;

knapsack(num,weight,profit,capacity);

You might also like