|
| 1 | +import heapq |
| 2 | +import math |
| 3 | +import sys |
| 4 | + |
| 5 | +from collections import defaultdict |
| 6 | + |
| 7 | +read = lambda: sys.stdin.readline().rstrip() |
| 8 | + |
| 9 | + |
| 10 | +class Problem: |
| 11 | + def __init__(self): |
| 12 | + self.v, self.e = map(int, read().split()) |
| 13 | + self.k = int(read()) |
| 14 | + |
| 15 | + self.graph = defaultdict(list) |
| 16 | + for start, end, distance in [map(int, read().split()) for _ in range(self.e)]: |
| 17 | + self.graph[start].append((end, distance)) |
| 18 | + |
| 19 | + def solve(self) -> None: |
| 20 | + distances = self.dijkstra() |
| 21 | + |
| 22 | + for vertex in range(self.v): |
| 23 | + print(distances[vertex] if distances[vertex] != math.inf else "INF") |
| 24 | + |
| 25 | + def dijkstra(self) -> list[float]: |
| 26 | + queue, distances = [(0, self.k)], [0 if idx == self.k else math.inf for idx in range(self.v + 1)] |
| 27 | + |
| 28 | + while queue: |
| 29 | + current_distance, current_vertex = heapq.heappop(queue) |
| 30 | + |
| 31 | + if current_distance > distances[current_vertex]: |
| 32 | + continue |
| 33 | + |
| 34 | + for next_vertex, distance in self.graph[current_vertex]: |
| 35 | + next_distance = current_distance + distance |
| 36 | + if next_distance < distances[next_vertex]: |
| 37 | + distances[next_vertex] = next_distance |
| 38 | + heapq.heappush(queue, (next_distance, next_vertex)) |
| 39 | + |
| 40 | + return distances[1:] |
| 41 | + |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + Problem().solve() |
0 commit comments