vinocastro

TSP for SOKOR

Jul 16th, 2021 (edited)
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. import itertools
  2. import math
  3.  
  4. # distance formula
  5. def distance(x1,y1,x2,y2):
  6.     x1,y1,x2,y2 = float(x1),float(y1),float(x2),float(y2)
  7.     return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
  8.  
  9. # processing inputs
  10. N = int(input())
  11. inputs = [] # input[i][0] = venue input[i][1] = longtitude in str  input[i][2] = latitude in str
  12. for i in range(N):
  13.     inputs.append(input().split())
  14.  
  15. # for generating the sequence of indeces
  16. sequences = list(itertools.permutations([i for i in range(1,N)]))
  17. for i in range(len(sequences)):
  18.     sequences[i] = list(sequences[i])
  19.     sequences[i].insert(0,0)
  20.  
  21. # travel
  22. def travel(seq):
  23.     total_cost = 0
  24.     for i in range(N):
  25.         if i == (N-1):
  26.             total_cost += distance(inputs[seq[i]][1],inputs[seq[i]][2],inputs[0][1],inputs[0][2])*111139
  27.         else:
  28.             total_cost += distance(inputs[seq[i]][1],inputs[seq[i]][2],inputs[seq[i+1]][1],inputs[seq[i+1]][2])*111139
  29.     return total_cost
  30.  
  31. # finding the sequence with the smallest cost
  32. min = 0
  33. if N <=2 :
  34.     min = travel(sequences[0])
  35.     min_seq = sequences[0]
  36. else:
  37.     for i in range(len(sequences)):
  38.         if i == 0:
  39.             min = travel(sequences[i])
  40.         else:
  41.             temp = travel(sequences[i])
  42.             if temp < min:
  43.                 min = temp
  44.                 min_seq = sequences[i]
  45.  
  46. # printing of output
  47. print(round(min,3))
  48. for j in min_seq:
  49.     print(inputs[j][0])
  50.  
Add Comment
Please, Sign In to add comment