Fractional Knapsack
You are packing a bag with weight capacity C. There are n items, and the i-th item has value vi and weight wi.
You do not have to take an entire item. You may take any fraction of an item, and both its weight and value scale proportionally. In particular, if you take weight x from item i (where 0≤x≤wi), then you gain value x⋅vi/wi.
What is the maximum total value you can obtain?
Input
The first line contains two integers n and C, the number of items and the knapsack capacity.
The next n lines each contain two integers vi and wi, the value and weight of an item.
Output
Print the maximum obtainable value as a floating-point number.
Your answer will be accepted if it has absolute or relative error at most 10−3.
Constraints
- 1≤n≤2⋅105
- 1≤C≤106
- 1≤vi,wi≤106
- If the exact answer is written as a reduced fraction p/q, then both p and q fit in signed 64-bit integers.
Example 1
3 3
8 6
9 4
10 5
6.75
Explanation
The second item has the highest value density: 9/4. With capacity 3, take 3/4 of that item and gain (3/4)⋅9=27/4.
Example 2
4 8
6 3
15 5
14 7
9 6
21.0
Explanation
Take the first two items completely. Their total weight is 3+5=8, and their total value is 6+15=21.
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.