lecture9_P5_backtracking.py
854 Bytes
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
import time
def promising(i,weight, total):
return ((weight+total >= W) and (weight==W or weight+w[i+1] <=W))
def s_s(i, weight, total, include):
#아주 조금 빨라지는 개선
if(weight+total == W) :
for j in range(i+1,n) :
include[j] = 1
print("sol",include)
elif(promising(i, weight, total)==True):
if(weight == W):
print("sol",include )
else:
include[i+1]=1
s_s(i+1, weight+w[i+1],total-w[i+1],include)
include[i+1]=0
s_s(i+1,weight,total-w[i+1],include)
w = 40*[0]
n=len(w)
for i in range(0,n):
w[i] = i+1
W=815
print("items =",w, "W =", W)
include = n*[0]
total=0
for k in w:
total+=k
start_t = time.time()
s_s(-1,0,total,include)
end_t = time.time()
print("time : ",str(end_t-start_t),'s')