티스토리 뷰
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b,c))
start, end = map(int, input().split())
def dijkstra(start ,end):
distance = [INF] * (n+1)
distance[start] = 0
q = []
heapq.heappush(q, (0, start))
while q:
cost, dest = heapq.heappop(q)
if distance[dest] < cost:
continue
for d, c in graph[dest]:
tmp = c + cost
if distance[d] > tmp:
distance[d] = tmp
heapq.heappush(q, (tmp, d))
return distance[end]
print(dijkstra(start, end))
백준에서 sys.stdin.readline을 해주지 않으면 시간초과가 난다.
아주 기본적인 다익스트라 알고리즘.
'코딩테스트 대비' 카테고리의 다른 글
[프로그래머스] 배달 (0) | 2022.03.07 |
---|---|
[백준] 1238번 파티 (0) | 2022.03.07 |
[백준] 9370번 미확인 도착지 (0) | 2022.03.07 |
[백준] 1504번 특정한 최단 경로 (0) | 2022.03.07 |
[백준] 1753번 최단경로 (0) | 2022.03.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- dfs
- n과m
- docker
- tensorflow
- torch
- 카카오
- 다익스트라
- 프로그래머스
- 이것이코딩테스트다
- version
- pytorch
- CUDA
- 백트래킹
- 파이썬
- shellscript
- 코딩테스트
- PIP
- torchscript
- LGSVL
- BFS
- 백준
- 최소신장트리
- 설치
- 동적프로그래밍
- notfound
- error
- numpy
- Python
- 설치하기
- matplotlib
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함