-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreedy_algorithm_Fractional_Knapsack_problem.cpp
More file actions
58 lines (57 loc) · 1.16 KB
/
Copy pathGreedy_algorithm_Fractional_Knapsack_problem.cpp
File metadata and controls
58 lines (57 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<cstdio>
#include<utility>
using namespace std;
#define s scanf
#define p printf
typedef struct
{
int price, weight,taken;
double price_per_weight;
}item;
item arr[100];
int main()
{
int n,i,j,max_weight;
while(s("%d",&n)==1)
{
for(i=1;i<=n;++i)
{
s("%d %d",&arr[i].price,&arr[i].weight);
arr[i].price_per_weight=(double)(arr[i].price)/(double)(arr[i].weight);
}
for(i=1;i<n;++i)
for(j=i+1;j<=n;++j)
if(arr[i].price_per_weight<arr[j].price_per_weight)
swap(arr[i].price_per_weight,arr[j].price_per_weight);
s("%d",&max_weight);
i=1;
double profit=0;
while(max_weight>0&&i<=n)
{
if(max_weight>arr[i].weight)
{
//profit+=arr[i].price;
profit+=arr[i].weight*arr[i].price_per_weight;
max_weight-=arr[i].weight;
++i;
}
else
{
profit+=(max_weight*arr[i].price_per_weight);
max_weight=0;
}
}
p("Max profit is: %lf\n\n",profit);
}
return 0;
}
/*
Input:
3
60 10
100 20
120 30
50
Output:
Max profit is: 240.000000
*/