-
Notifications
You must be signed in to change notification settings - Fork 2
/
tsp.py
executable file
·70 lines (57 loc) · 1.65 KB
/
tsp.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/pypy
import numpypy as np
import sys
import itertools as it
def get_value(s):
v = np.int32(0)
for i in s:
if i == 0: continue
v = v | 1 << (i-1)
return v
def get_value_without_v(s,skip):
v = np.int32(0)
for i in s:
if i ==0 or i == skip:continue
v = v | 1 << (i-1)
return v
def get_dist(data,i,j):
return np.sqrt((data[i][0]-data[j][0])*(data[i][0]-data[j][0])+
(data[i][1]-data[j][1])*(data[i][1]-data[j][1]))
def solve(data,size):
max_size=2**size
A = np.ones([max_size,size],float)*sys.float_info.max
A[0,0] = 0
for m in range(2,size+1):
subsets = it.combinations(range(1,size),m-1)
for s in subsets:
s = (0,)+s
v = get_value(s)
for j in s:
if 0 == j: continue
vmin = sys.float_info.max
v_tmp = get_value_without_v(s,j)
for k in s:
if k == j: continue
v_cand = A[v_tmp,k] + get_dist(data,k,j)
if v_cand < vmin:
vmin = v_cand
A[v,j] = vmin
rst = sys.float_info.max
v = get_value(range(size))
for j in range(size):
v_cand = A[v,j] + get_dist(data,j,0)
if v_cand < rst:
rst = v_cand
return rst
def main():
print "Starting solving TSP"
file=open("data/tsp.txt")
size = int(file.readline())
cities=[]
for line in file.readlines():
(x,y) = [float(x) for x in line.split()]
cities.append((x,y))
print cities
print "TSP path length:",solve(cities,size)
if __name__ == '__main__':
main()