forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01 knapsack
More file actions
56 lines (52 loc) · 1.04 KB
/
01 knapsack
File metadata and controls
56 lines (52 loc) · 1.04 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
#include <bits/stdc++.h>
#include <iomanip>
typedef long long ll;
using namespace std;
class Items
{
public:
ll value;
ll weight;
double ratio;
};
bool cmp(Items i1, Items i2)
{
return (i1.ratio>i2.ratio);
}
int main()
{
ll n,capacity,tempweight(0),tempval(0);
double val(0);
cin >> n >> capacity;
Items item[n];
for(ll i=0;i<n;i++)
{
cin>>item[i].value>>item[i].weight;
item[i].ratio = (double)item[i].value/item[i].weight;
tempweight += item[i].weight;
tempval += item[i].value;
}
if(tempweight < capacity)
{
cout<<tempval<<endl;
exit(0);
}
sort(item, item+n, cmp);
for(ll i=0;i<n;i++)
{
if(capacity == 0)
break;
else if(item[i].weight < capacity)
{
val += item[i].value;
capacity -= item[i].weight;
}
else
{
val = val + item[i].ratio*capacity;
capacity =0;
}
}
cout<<fixed<<setprecision(4)<<val<<endl;
return 0;
}