Saturday, July 30, 2016

The Fractional Knapsack Problem With Greedy Algorithom

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <conio.h>


using namespace std;

struct Product{
double b;
double w;
double v;
double c;
};

bool compare(Product p1, Product p2){
if(p1.v>p2.v){
return true;
}
else{
return false;
}
}

int main(){
Product p[100];
int n,i;
double w,b,v;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%lf",&w);
scanf("%lf",&b);
p[i].w = w;
p[i].b = b;
p[i].v = b/w;
}
sort(p,p+n, compare);

int k=10,f=0,t=0;
for(i=0;i<n;i++){
        p[i].c=0;
}
i=0;
while(f<k){
        if(p[i].w <=(k-f)){
            t += p[i].b;
            f += p[i].w;
            p[i].c = p[i].w;
        }
        else{
            t += (k-f)*p[i].v;
            p[i].c = k-f;
             f += k-f;
        }
        i++;
}
cout <<"Total profit  :  " <<t << " $\n";

for(i=0;i<n;i++)
        cout << p[i].c << " \n";

getch();
return 0;
}

No comments:

Post a Comment