RosettaCodeData/Task/Knapsack-problem-0-1/Python/knapsack-problem-0-1-4.py

31 lines
662 B
Python
Raw Permalink Normal View History

2026-04-30 12:34:36 -04:00
n, G = 5, 5 # KNAPSACK 0-1 DANILIN
2026-02-01 16:33:20 -08:00
N = n + 1 # rextester.com/BCKP19591
a = 2 ** N
L, C, j, q, s, d, e = [1]*n, [1]*n, [1]*n, [0]*a, [0]*a, [0]*a, [""]*a
2023-07-01 11:58:00 -04:00
from random import randint
2026-02-01 16:33:20 -08:00
for i in range(n):
L[i] = randint(1, 3)
C[i] = 10+randint(1, 9)
print(i+1, L[i], C[i])
2023-07-01 11:58:00 -04:00
print()
2026-02-01 16:33:20 -08:00
for h in range(a-1, (a-1)//2, -1):
b = str(bin(h))
e[h] = b[3:len(b)]
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
for k in range(n):
j[k] = int(e[h][k])
q[h] = q[h]+L[k]*j[k]*C[k]
d[h] = d[h]+L[k]*j[k]
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
if d[h] <= G:
2023-07-01 11:58:00 -04:00
print(e[h], G, d[h], q[h])
print()
2026-02-01 16:33:20 -08:00
max, m = 0, 1
2023-07-01 11:58:00 -04:00
for i in range(a):
2026-02-01 16:33:20 -08:00
if d[i] <= G and q[i] > max:
2026-04-30 12:34:36 -04:00
max, m = q[i], i
2026-02-01 16:33:20 -08:00
print(d[m], q[m], e[m])