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
풀이
다익스트라 알고리즘을 사용해 풀었습니다.
※ heap에서 꺼낸 비용보다 cost의 비용이 더 작다면 넘어갑니다. (time limit 방지)
코드
파이썬
import sys
from heapq import heappush, heappop
input = sys.stdin.readline
INF = sys.maxsize
V, E = map(int, input().split())
K = int(input())
graph = [[] for _ in range(V + 1)]
cost = [INF] * (V + 1)
for _ in range(E):
u, v, w = map(int, input().split())
graph[u].append((w, v))
heap = []
cost[K] = 0
heappush(heap, (0, K))
while heap:
c, x = heappop(heap)
if cost[x] < c:
continue
for nc, nx in graph[x]:
if cost[nx] > c + nc:
cost[nx] = c + nc
heappush(heap, (cost[nx], nx))
for c in cost[1:]:
print(c if c != INF else "INF")
728x90
'🚩 코딩테스트 > 알고리즘' 카테고리의 다른 글
[백준] 7569번: 토마토 (0) | 2023.05.11 |
---|---|
[백준] 10026번: 적록색약 (0) | 2023.05.11 |
[백준] 14500번: 테트로미노 (1) | 2023.05.10 |
[백준] 16586번: 치킨 배달 (0) | 2023.05.09 |
[백준] 10986번: 나머지 합 (0) | 2023.05.09 |
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
풀이
다익스트라 알고리즘을 사용해 풀었습니다.
※ heap에서 꺼낸 비용보다 cost의 비용이 더 작다면 넘어갑니다. (time limit 방지)
코드
파이썬
import sys
from heapq import heappush, heappop
input = sys.stdin.readline
INF = sys.maxsize
V, E = map(int, input().split())
K = int(input())
graph = [[] for _ in range(V + 1)]
cost = [INF] * (V + 1)
for _ in range(E):
u, v, w = map(int, input().split())
graph[u].append((w, v))
heap = []
cost[K] = 0
heappush(heap, (0, K))
while heap:
c, x = heappop(heap)
if cost[x] < c:
continue
for nc, nx in graph[x]:
if cost[nx] > c + nc:
cost[nx] = c + nc
heappush(heap, (cost[nx], nx))
for c in cost[1:]:
print(c if c != INF else "INF")
728x90
'🚩 코딩테스트 > 알고리즘' 카테고리의 다른 글
[백준] 7569번: 토마토 (0) | 2023.05.11 |
---|---|
[백준] 10026번: 적록색약 (0) | 2023.05.11 |
[백준] 14500번: 테트로미노 (1) | 2023.05.10 |
[백준] 16586번: 치킨 배달 (0) | 2023.05.09 |
[백준] 10986번: 나머지 합 (0) | 2023.05.09 |