avp26/u11/knapsack.py
Maksym Kurets 202bfd9b38 u11 update
2026-12-04 22:09:33 +01:00

56 lines
1.2 KiB
Python

def maximum_value(maximum_weight, items):
if not items or maximum_weight <= 0:
return 0
stav = {0: 0}
for item in items:
w = item["weight"]
v = item["value"]
Novystav = dict(stav)
for currW, currV in stav.items():
NEwW = currW + w
if NEwW <= maximum_weight:
NewV = currV + v
if NewV > Novystav.get(NEwW, 0):
Novystav[NEwW] = NewV
stav = Novystav
return max(stav.values())
def maximum_value_with_items(maximum_weight, items):
if not items or maximum_weight <= 0:
return 0, []
stav = {0: (0,[])}
w = item["weight"]
v = item["value"]
Novystav = dict(stav)
for currW,(currV, vibir) in stav.items():
for currW,(currV, vibir) in stav.items():
NEwW = currW + w
if NEwW <= maximum_weight:
NewV = currV + v
if NewV > Novystav.get(NEwW, (0, []))[0]:
Novystav[NEwW] = (NewV, vibir + [item])
stav = Novystav
BV = 0
Bvibir = []
for v, vibir in stav.values():
if v >BV:
BV = v
Bvibir = vibir
return BV, Bvibir