假设一共有N件物品,第 i 件物品的价值为 Vi ,重量为Wi,一个小偷有一个最多只能装下重量为W的背包,在总量不超过W的情况下让总值尽量高。每一个物品都可以取走一部分,价值和重量按比例计算,求最大总价值。
注意:每个物品可以只拿一部分,因此一定可以让总量恰好为W
w = [1, 2, 4, 5]
v = [3, 4, 1, 4]
W = 3.5
def f(w:list, v:list, W:int) -> float:
w_v = sorted(zip(w, v), key=lambda x: x[1]/x[0], reverse=True)
c_p = 0.0
c_w = 0.0
for w, v in w_v:
_c_w = c_w + w
if _c_w < W:
c_p += v
c_w += w
continue
if c_w < W:
left_w = W - c_w
c_p += left_w * (v/w)
break
break
return c_p
n, W, *_ = map(int, input().split())
w_v = []
for i in range(n):
w_v.append(list(map(int, input().split())))
def f(w_v:list, W:int) -> str:
w_v = sorted(w_v, key=lambda x: x[1]/x[0], reverse=True)
c_p = 0.0
c_w = 0.0
for w, v in w_v:
_c_w = c_w + w
if _c_w < W:
c_p += v
c_w += w
continue
if c_w < W:
left_w = W - c_w
c_p += left_w * (v/w)
break
break
return '{:.2f}'.format(c_p)
print(f(w_v, W))