Advertisement
halaluddin

Dijkstra

Nov 21st, 2019
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. from heapq import heappop, heappush, heapify
  2. from sys import maxsize
  3.  
  4.  
  5. class Graph:
  6.     def __init__(self, vertices):
  7.         self.v = vertices+1
  8.         self.cost = [[0]*(vertices+1) for _ in range(vertices+1)]
  9.  
  10.     def add_edges(self, src, dest, weight):
  11.         if self.cost[src][dest] and self.cost[dest][src]:
  12.             if self.cost[src][dest] > weight and self.cost[dest][src] > weight:
  13.                 self.cost[src][dest] = weight
  14.                 self.cost[dest][src] = weight
  15.         else:
  16.             self.cost[src][dest] = weight
  17.             # Becouse, Given Graph is undirected.
  18.             self.cost[dest][src] = weight
  19.  
  20.     def dijkstra(self, source):
  21.  
  22.         Q = [source]
  23.         distance = [maxsize] * self.v
  24.         distance[source] = 0
  25.         heapify(Q)
  26.  
  27.         while Q:
  28.  
  29.             u = heappop(Q)
  30.  
  31.             for v in range(self.v):
  32.                 if self.cost[u][v] and distance[u] + self.cost[u][v] < distance[v]:
  33.                     distance[v] = distance[u] + self.cost[u][v]
  34.                     heappush(Q, v)
  35.                
  36.         return distance[1:]
  37.  
  38.  
  39.  
  40. def shortestReach(n, edges, s):
  41.    
  42.     g = Graph(n)
  43.     for tpl in edges:
  44.         g.add_edges(tpl[0], tpl[1], tpl[2])
  45.    
  46.     shortest_distance = g.dijkstra(s)
  47.  
  48.     return shortest_distance
  49.    
  50.  
  51.  
  52. if __name__ == '__main__':
  53.  
  54.     t = int(input())
  55.  
  56.     for t_itr in range(t):
  57.         nm = input().split()
  58.  
  59.         n = int(nm[0])
  60.  
  61.         m = int(nm[1])
  62.  
  63.         edges = []
  64.  
  65.         for _ in range(m):
  66.             edges.append(list(map(int, input().rstrip().split())))
  67.  
  68.         s = int(input())
  69.  
  70.         result = shortestReach(n, edges, s)
  71.  
  72.         for i in result:
  73.             if i == 0: continue
  74.             elif i == maxsize: print(-1, end=' ')
  75.             else: print(i, end=' ')
  76.         print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement