728x90
반응형
https://www.acmicpc.net/problem/1753
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다.
www.acmicpc.net
Python
import heapq
import sys
input = sys.stdin.readline
v, e = map(int, input().split())
k = int(input())
graph = [[] for _ in range(v+1)]
visit = [0] * (v+1)
dist = ["INF"] * (v+1)
for _ in range(e):
a, b, c = map(int, input().split())
graph[a].append((b, c))
def di(start): # 최소 힙으로 빠르게 가장 작은 노드 찾기
global visit, dist
hq = []
heapq.heappush(hq, (0, start))
dist[start] = 0
now = start
while hq:
d, now = heapq.heappop(hq)
if dist[now] >= d:
for i in graph[now]:
if dist[i[0]] == "INF" or dist[i[0]] > d+i[1]:
dist[i[0]] = d+i[1]
heapq.heappush(hq, (dist[i[0]], i[0]))
di(k)
print("\n".join(map(str, dist[1:])))
+) heapq 라이브러리
https://wakaranaiyo.tistory.com/247
[Python] heapq 라이브러리 살펴보기
사용 방법 heap = [] # 비어있는 heap 생성 heappush(heap, item) # heap 값을 추가 item = heappop(heap) # heap에서 가장 작은 값을 삭제 item = heap[0] # 삭제 없이 heap에서 가장 작은 값 보기 heapify(x) #..
wakaranaiyo.tistory.com
728x90
반응형
'Algorithm Problems' 카테고리의 다른 글
[Python] 그래프 최단경로 알고리즘 정리 (0) | 2021.08.23 |
---|---|
[백준][Python] 1916번 최소비용 구하기 - 그래프, 다익스트라 (0) | 2021.08.23 |
[백준][Python] 1504번 특정한 최단경로 - 그래프, BFS (0) | 2021.08.19 |
[백준][Python] 1931번 회의실 배정 - DP (0) | 2021.08.16 |
[백준][Python] 1043번 거짓말 - 그래프, DFS (0) | 2021.08.12 |