-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathknapsack_bt_recursive.py
More file actions
56 lines (45 loc) · 1.54 KB
/
knapsack_bt_recursive.py
File metadata and controls
56 lines (45 loc) · 1.54 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
# 0-1 Knapsack backtracking, recursive
# By James Lao
import time
import sys
import threading
def knapsack(vw, limit):
def bound(v, w, j):
if j >= len(vw) or w > limit:
return -1
else:
while j < len(vw) and w + vw[j][1] <= limit:
v, w, j = v + vw[j][0], w + vw[j][1], j + 1
if j < len(vw):
v += (limit - w) * vw[j][0] / (vw[j][1] * 1.0)
return v
def traverse(v, w, j):
nonlocal maxValue
# print(v,w,j, bound(v,w,j))
if bound(v, w, j) >= maxValue: # promising w/ j
if w + vw[j][1] <= limit:
maxValue = max(maxValue, v + vw[j][0])
traverse(v + vw[j][0], w + vw[j][1], j + 1)
if j < len(vw) - 1: # promising w/o j
traverse(v, w, j + 1)
return
maxValue = 0
traverse(0, 0, 0)
return maxValue
def main():
with open(sys.argv[1] if len(sys.argv) > 1 else sys.exit(1)) as f:
limit, n = map(int, f.readline().split())
vw = [] # value, weight, value density
for ln in f.readlines():
vl, wl = tuple(map(int, ln.split()))
vw.append([vl, wl, vl / (wl * 1.0)])
start = time.time()
A = knapsack(sorted(vw, key=lambda x: x[2], reverse=True), limit)
end = time.time()
print(A)
print(end - start)
if __name__ == "__main__":
threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(20000)
thread = threading.Thread(target=main)
thread.start()