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
1. 난이도 골드4 (🥇)
2. 내가 작성한 코드
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
v,e = map(int,input().rstrip().split()) #v는 정점, e는 간선
start = int(input().rstrip()) #시작 정점 번호
distance = [INF] * (v+1)
graph = [[] for _ in range(v+1)]
for i in range(e):
u,v,w = map(int,input().rstrip().split()) #u시작 v도착 w가중치
graph[u].append((v,w))
def dij(start):
queue = []
heapq.heappush(queue,(0,start)) #시작점의 dist는 0
distance[start] = 0
while queue:
dist, now = heapq.heappop(queue)
if distance[now] < dist: #이미 처리한 정점은 처리x
continue
for i in graph[now]:
cost = dist + i[1]
if distance[i[0]] > cost:
distance[i[0]] = cost
heapq.heappush(queue,(cost,i[0]))
dij(start)
for i in distance[1:]:
if i == INF:
print("INF")
else:
print(i)
완전 전형적인 다익스트라 문제이다.
이코테로 공부하자마자 풀어봤는데 쉽게 맞을 수 있었다.
'🔅코딩테스트 공부🔅 > ❗백준' 카테고리의 다른 글
[백준] 1504번 특정한 최단 경로(python) (1) | 2023.02.24 |
---|---|
[백준] 1916번 최소비용 구하기(python) (0) | 2023.02.24 |
[백준] 2206번 벽 부수고 이동하기(python) (0) | 2023.02.23 |
[백준] 1874번 스택수열(python) (0) | 2023.02.23 |
[백준] 4963번 섬의 개수(python) (0) | 2023.02.22 |
댓글