[Algorithm] 최단 경로 - 전보

Jifrozen·2021년 8월 18일
0

Algorithm

목록 보기
44/70

전보

import heapq
import sys

input = sys.stdin.readline
INF = int(1e9)

n, m, start = map(int, input().split())
graph = [[] for i in range(n + 1)]
distance = [INF] * (n + 1)

for _ in range(m):
    x, y, z = map(int, input().split())
    graph[x].append((y, z))


def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 0
    while q:
        dist, now = heapq.heappop(q)
        if distance[now] < dist:
            continue
        for i in graph[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))


dijkstra(start)

count = 0
max_distance = 0
for d in distance:
    if d != INF:
        count += 1
        max_distance = max(max_distance, d)

print(count - 1, max_distance)

한 도시에서 다른 도시까지의 최단경로를 구해 그 중 가장 먼 거리를 구하는 문제이다.
시간복잡도가 여유롭지 않기 때문에 다익스트라 알고리즘을 이용해야한다.

0개의 댓글