Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. import heapq
  2.  
  3. def shortest_path(G, start, end):
  4.    def flatten(L):       # Flatten linked list of form [0,[1,[2,[]]]]
  5.       while len(L) > 0:
  6.          yield L[0]
  7.          L = L[1]
  8.  
  9.    q = [(0, start, ())]  # Heap of (cost, path_head, path_rest).
  10.    visited = set()       # Visited vertices.
  11.    while True:
  12.       (cost, v1, path) = heapq.heappop(q)
  13.       if v1 not in visited:
  14.          visited.add(v1)
  15.          if v1 == end:
  16.             #print cost
  17.             return list(flatten(path))[::-1] + [v1],cost
  18.          path = (v1, path)
  19.          for (v2, cost2) in G[v1].iteritems():
  20.             if v2 not in visited:
  21.                heapq.heappush(q, (cost + cost2, v2, path))
  22.  
  23.  
  24. def remove_node(graph, key):
  25.     for k,v in graph.items():
  26.         #print v
  27.         #for edges in v:
  28.         for n,w in v.items():
  29.             if n==key:
  30.                 del v[n]
  31.     return graph
  32.  
  33.  
  34.  
  35. n,e = [int(i) for i in raw_input().spit(' ')]
  36. graph={}
  37. for i in xrange(1,n+1):
  38.     graph[i]={}
  39.    
  40. for j in xrange(e):
  41.     v1,v2,w = raw_input().split(' ')
  42.     graph[v1][v2] = int(w)
  43.     graph[v2][v1] = int(w)
  44.  
  45.  
  46.  
  47. path1,cost1 = shortest_path(graph,'1',n)
  48. path = path1
  49. path1 = path1[1:-1]
  50.  
  51. for item in path1:
  52.     gp1=remove_node(graph,item)
  53. for item in path1:
  54.     del gp1[item]
  55.  
  56. path2,cost2 = shortest_path(graph,n,'1')
  57.  
  58. print cost1+cost2
  59.  
  60. raw_input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement