-
[다익스트라 알고리즘] 특정한 최단 경로Algorithms/Shortest Path 2021. 8. 13. 16:29
기출 : 백준 #1504
1 -> v1 -> v2 -> n
1 -> v2 -> v1 -> n
위의 두 가지 경로를 고려하여 최솟값을 출력하면 된다
from heapq import heappop, heappush INF = int(1e9) n, e = map(int,input().split()) graph = [[]for _ in range(n+1)] queue = list() for _ in range(e): x,y,w = map(int,input().split()) graph[x].append((w, y)) graph[y].append((w, x)) v1, v2 = map(int,input().split()) def dijkstra(start, end): distance = [INF for _ in range(n+1)] distance[start] = 0 heappush(queue, (0, start)) while queue: curVal, cur = heappop(queue) if distance[cur] < curVal: continue for nextVal, next in graph[cur]: if distance[next] > curVal + nextVal: distance[next] = curVal + nextVal heappush(queue, (curVal + nextVal, next)) return distance[end] way1 = dijkstra(1,v1) + dijkstra(v1,v2) + dijkstra(v2, n) way2 = dijkstra(1,v2) + dijkstra(v2,v1) + dijkstra(v1, n) minWay = min(way1, way2) if minWay>=INF: print(-1) else: print(minWay)
'Algorithms > Shortest Path' 카테고리의 다른 글
[다익스트라 알고리즘] 케빈 베이컨의 6단계 법칙 (0) 2021.08.29 [다익스트라 알고리즘] 알고스팟 (0) 2021.08.15 [다익스트라 알고리즘] 최소비용 구하기 (0) 2021.08.13 [다익스트라 알고리즘] 최단경로 (0) 2021.08.13 [최단 경로 알고리즘] 문제풀이 전략 #2 플로이드 워셜 알고리즘 (0) 2021.02.17