-
알고리즘: 백준 11779번 최소비용 구하기2 (feat.python)알고리즘/백준(BaekJoon) 2021. 1. 15. 13:29
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
import sys import heapq read = sys.stdin.readline n = int(read()) m = int(read()) graph = {i:[] for i in range(1, n+1)} for _ in range(m): s, e, w = map(int, read().split()) graph[s].append([w, e]) start, end = map(int, read().split()) INF = sys.maxsize dist = [[INF, 0] for _ in range(n+1)] dist[start] = [0, start] hq = [] heapq.heappush(hq, [0, start]) route = [] def dijkstra(): while hq: cw, cn = heapq.heappop(hq) for nw, nn in graph[cn]: next_weight = nw + cw if next_weight <= dist[nn][0]: dist[nn] = [next_weight, cn] heapq.heappush(hq, [next_weight, nn]) def find_route(end): route.append(end) if end != start: find_route(dist[end][1]) dijkstra() find_route(end) route = route[::-1] print(dist[end][0]) print(len(route)) for r in route: print(r, end=' ')
반응형'알고리즘 > 백준(BaekJoon)' 카테고리의 다른 글
알고리즘: 백준 2211번 네트워크 복구 (feat.python) (0) 2021.01.15 알고리즘: 백준 10282번 해킹 (feat. python) (0) 2021.01.15 알고리즘: 백준 2665번 미로만들기 (feat.python) (0) 2021.01.13 알고리즘: 백준 4485번 녹색 옷 입은 애가 젤다지? (feat. python) (0) 2021.01.12 알고리즘: 백준 13549번 숨바꼭질 (feat. python) (0) 2021.01.12