[파이썬] 백준 1753 : 최단경로 (골드4)
풀이
방향성 생각
방향 그래프의 node A에서 다른 노드까지의 거리를 구하는 문제
입력 크기를 보면 node = 20000에 edges = 300000이라 다익스트라로 풀이.
주의할점은 node간 중복 간선이 주어져서 처리를 해야한다.
defaultdict로 이중 딕셔너리 만들어서 최솟값으로 갱신하는 방식으로 풀이
전체코드
from collections import defaultdict as dd
import heapq as hq
import sys
input = lambda : sys.stdin.readline().rstrip()
N,K = map(int,input().split())
start = int(input())
# 방향 그래프 : edges[a][b] = cost (a->b로 가는 cost 최소값으로 갱신하기)
edges = dd(lambda : dd(lambda : float('inf')))
for _ in range(K):
a,b,cost = map(int,input().split())
edges[a][b] = min(edges[a][b],cost)
V = [float('inf')]*(N+1)
V[start] = 0
heap = [(0,start)]
while heap:
c,x = hq.heappop(heap)
for nx,cost in edges[x].items():
nc = c+cost
if nc < V[nx]:
V[nx] = nc
hq.heappush(heap,(nc,nx))
for cost in V[1:]:
print(cost if cost != float('inf') else 'INF')
코멘트
- 기본 다익스트라 문제.
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 14868 : 문명 (플레4) (0) | 2024.11.22 |
---|---|
[파이썬] 백준 11779 : 최소비용 구하기 2 (골드3) (0) | 2024.11.21 |
[파이썬] 백준 1916 : 최소비용 구하기 (골드5) (0) | 2024.11.21 |
[파이썬] 백준 2479 : 경로찾기 (골드4) (0) | 2024.11.16 |
[파이썬] 백준 1240 : 노드 사이의 거리 (골드5) (0) | 2024.11.15 |
[파이썬] 백준 1595 : 북쪽나라의 도로 (골드4) (0) | 2024.10.01 |
[파이썬] 백준 1368 : 물대기 (골드2) (0) | 2024.09.21 |
댓글