프로그래밍/Python

[Python] 백준 1504 특정한 최단 경로

모영이 2021. 2. 16. 17:30

 

1504번: 특정한 최단 경로

첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존

www.acmicpc.net

다익스트라 알고리즘

1 -> N까지 가야하고 v1, v2를 거쳐야 한다. 양뱡향이므로 그래프에 저장할 때 둘 다 저장해야한다. 우선순위 힙을 사용하고 heappush()로 값을 넣고 heappop()으로 값을 추출한다.

 

1) 1에서 출발, v1에서 출발, v2에서 출발하는 세가지 distance를 구한다.

2) 1 -> v1 -> v2 -> N 과 1 -> v2 -> v1 -> N을 비교해서 최솟값이 답이다.

3) 갈 수 없을 때 예외처리

 

전체 코드

import sys
import heapq
import collections
input = sys.stdin.readline

N, E = map(int, input().split())

graph = collections.defaultdict(list)
for _ in range(E):
    a, b, c = map(int, input().split())
    graph[a].append((c, b))
    graph[b].append((c, a))
v1, v2 = map(int, input().split())
def dijkstra(start: int):
    distance = [sys.maxsize for _ in range(N+1)]
    distance[start] = 0
    heap = []
    heapq.heappush(heap, (0, start))

    while heap:
        current_distance, current_node = heapq.heappop(heap)
        if distance[current_node] < current_distance:
            continue
        for d, n in graph[current_node]:
            next_distance = d + current_distance
            if next_distance < distance[n]:
                distance[n] = next_distance
                heapq.heappush(heap, (next_distance, n))
    return distance

start_d = dijkstra(1)
v1_d = dijkstra(v1)
v2_d = dijkstra(v2)
fast_d = min(start_d[v1] + v1_d[v2] + v2_d[N], start_d[v2] + v2_d[v1] + v1_d[N])
if fast_d < sys.maxsize:
    print(fast_d)
else:
    print(-1)

'프로그래밍 > Python' 카테고리의 다른 글

[Python] 백준 4195 친구 네트워크  (0) 2021.02.19
[Python] 백준 20040 사이클 게임  (0) 2021.02.16
[Python] 백준 11404 플로이드  (0) 2021.02.16
[Python] 백준 2470 두 용액  (0) 2021.02.15
[Python] 백준 11399 ATM  (0) 2021.02.15