0% found this document useful (0 votes)
15 views10 pages

DAA Practical 3

Daa practice 3

Uploaded by

Abhishek Agrawal
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)
15 views10 pages

DAA Practical 3

Daa practice 3

Uploaded by

Abhishek Agrawal
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/ 10

WAP in C++ to solve fractional knapsack using greedy algorithm with class.

#include<iostream.h>
#include<conio.h>
class fraction{
public :
double a[50],aa[50];
int n,temp,i,j;
int constraints,u;
double x[20],profit,s[10];
void func(double a[50],double aa[50],int n,int u)
{
profit=0;

for(i=0;i<n;i++)
{
s[i]=a[i]/aa[i];
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]<s[j])
{
temp=s[j];
s[j]=s[i];
s[i]=temp;

temp=a[j];
a[j]=a[i];
a[i]=temp;

temp=aa[j];
aa[j]=aa[i];
aa[i]=temp;
}
}
}
for(i=0;i<n;i++)
{
x[i]=0;
}
for(i=0;i<n;i++)
{
if(aa[i]>u)
{
break;
}
else
{
x[i]=1.0;
profit=profit+a[i];
u=u-aa[i];
}
}
if(i<n)
{
x[i]=u/aa[i];
profit=profit+a[i]*x[i];
}
for(i=0;i<n;i++)
cout<<x[i];
cout<<endl;

cout<<profit<<endl;
}

};

void main()
{

clrscr();
int n,constraints,i;
double v[50],w[50];
cout<<"enter object and constraints"<<endl;
cin>>n>>constraints;
cout<<"Enter profit and weight"<<endl;
for(i=0;i<n;i++)
{
cin>>v[i];
cin>>w[i];
}
fraction f;
f.func(v,w,n,constraints);
getch();
}

You might also like