Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 41bfe2a

Browse files
[Gold V] Title: 최단경로, Time: 716 ms, Memory: 66112 KB -BaekjoonHub
1 parent f25b6b3 commit 41bfe2a

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# [Gold V] 최단경로 - 1753
2+
3+
[문제 링크](https://www.acmicpc.net/problem/1753)
4+
5+
### 성능 요약
6+
7+
메모리: 66112 KB, 시간: 716 ms
8+
9+
### 분류
10+
11+
다익스트라(dijkstra), 그래프 이론(graphs)
12+
13+
### 문제 설명
14+
15+
<p>방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.</p>
16+
17+
### 입력
18+
19+
<p>첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.</p>
20+
21+
### 출력
22+
23+
<p>첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.</p>
24+
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 최단경로
2+
import heapq, sys
3+
input = sys.stdin.readline
4+
INF = int(1e9)
5+
6+
# n : 노드의 수 / m : 간선의 수
7+
n, m = map(int, input().split())
8+
9+
# start : 시작노드
10+
start = int(input())
11+
12+
# 노드정보
13+
graph = [[] for _ in range(n+1)]
14+
15+
# 방문정보
16+
visited = [False] * (n+1)
17+
18+
# 최단 거리 테이블 (무한으로 초기화)
19+
distance = [INF] * (n+1)
20+
21+
# 모든 간선 정보 입력받기
22+
for _ in range(m):
23+
a, b, c = map(int, input().split()) # a -> b (비용 c)
24+
graph[a].append((b, c))
25+
26+
def dijkstra(start):
27+
q = []
28+
heapq.heappush(q, (0, start))
29+
distance[start] = 0
30+
31+
while q:
32+
dist, v = heapq.heappop(q) # 최단거리가 가장 짧은 노드 반환
33+
if distance[v] < dist: # 현재 노드가 이미 처리되었으면
34+
continue # 건너뛰기
35+
for i in graph[v]: # 현재 노드와 연결된 노드 확인
36+
cost = dist + i[1]
37+
if cost < distance[i[0]]: # 현재 노드를 거치는 게 더 빠를 경우
38+
distance[i[0]] = cost
39+
heapq.heappush(q, (cost, i[0]))
40+
41+
dijkstra(start)
42+
43+
for i in range(1, n+1):
44+
if distance[i] == INF:
45+
print("INF")
46+
else:
47+
print(distance[i])

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /