Skip to content

Commit 3253bfe

Browse files
committed
[Gold IV] Title: 최단경로, Time: 852 ms, Memory: 103112 KB -BaekjoonHub
1 parent b8264f5 commit 3253bfe

File tree

2 files changed

+156
-0
lines changed

2 files changed

+156
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# [Gold IV] 최단경로 - 1753
2+
3+
[문제 링크](https://www.acmicpc.net/problem/1753)
4+
5+
### 성능 요약
6+
7+
메모리: 103112 KB, 시간: 852 ms
8+
9+
### 분류
10+
11+
그래프 이론, 최단 경로, 데이크스트라
12+
13+
### 제출 일자
14+
15+
2026년 2월 28일 23:22:51
16+
17+
### 문제 설명
18+
19+
<p>방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.</p>
20+
21+
### 입력
22+
23+
<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>
24+
25+
### 출력
26+
27+
<p>첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.</p>
28+
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
"use strict";
2+
3+
const fs = require("fs");
4+
const input = fs
5+
.readFileSync(process.platform === "linux" ? "/dev/stdin" : "./input.txt")
6+
.toString()
7+
.trim()
8+
.split("\n");
9+
10+
/**
11+
* 우선순위 힙 구현
12+
*/
13+
14+
class MinHeap {
15+
constructor() {
16+
this.heap = [];
17+
}
18+
push(val) {
19+
this.heap.push(val);
20+
this.bubbleUp();
21+
}
22+
pop() {
23+
if (this.size() === 1) return this.heap.pop();
24+
const top = this.heap[0];
25+
this.heap[0] = this.heap.pop(); //맨 뒤에 있는걸 빼서 맨 앞으로 씌우기
26+
this.bubbleDown();
27+
return top;
28+
}
29+
size() {
30+
return this.heap.length;
31+
}
32+
bubbleUp() {
33+
let index = this.heap.length - 1;
34+
35+
while (index > 0) {
36+
let parent = Math.floor((index - 1) / 2);
37+
38+
if (this.heap[parent][1] > this.heap[index][1]) {
39+
[this.heap[parent], this.heap[index]] = [
40+
this.heap[index],
41+
this.heap[parent],
42+
];
43+
index = parent;
44+
} else {
45+
break;
46+
}
47+
}
48+
}
49+
bubbleDown() {
50+
let index = 0;
51+
//왼쪽 자식이 있다 => 내려갈 가능성이 있음을 뜻함
52+
while (index * 2 + 1 < this.heap.length) {
53+
let left = index * 2 + 1,
54+
right = index * 2 + 2,
55+
smallerChild = left; //왼쪽이 더 작다고 가정
56+
57+
//오른쪽에 자식이 있고, 오른쪽이 왼쪽보다 작다면
58+
// 더 작은쪽과 바꿔야하므로 smallerChild를 오른쪽으로 교체
59+
if (
60+
right < this.heap.length &&
61+
this.heap[right][1] < this.heap[left][1]
62+
) {
63+
smallerChild = right;
64+
}
65+
66+
//자식 중 제일 작은 것보다 더 작으면 멈추기
67+
if (this.heap[index][1] <= this.heap[smallerChild][1]) {
68+
break;
69+
} else {
70+
//아니라면 자리를 바꾸고 아래로 내려감
71+
[this.heap[index], this.heap[smallerChild]] = [
72+
this.heap[smallerChild],
73+
this.heap[index],
74+
];
75+
index = smallerChild;
76+
}
77+
}
78+
}
79+
}
80+
81+
const [V, E] = input[0].split(" ").map(Number);
82+
const K = +input[1]; //시작정점 번호
83+
84+
const adj = Array.from({ length: V + 1 }, () => []); //인접리스트
85+
86+
for (let i = 2; i < input.length; i++) {
87+
const [u, v, w] = input[i].split(" ").map(Number);
88+
adj[u].push([v, w]); //u번 정점에서 v번 정점으로 가는 가중치 w인 간선
89+
}
90+
91+
const dist = Array(V + 1).fill(Infinity);
92+
93+
function dijkstra(start) {
94+
const pq = new MinHeap();
95+
dist[start] = 0;
96+
97+
pq.push([start, 0]); //[노드번호, 거리]
98+
99+
while (pq.size() > 0) {
100+
const [curr, d] = pq.pop();
101+
102+
if (dist[curr] < d) continue; //꺼낸 거리가 이미 기록된 거리보다 크다면 무시
103+
104+
//현재 노드와 연결된 인접 노드 확인
105+
for (const [next, weight] of adj[curr]) {
106+
const nextDist = d + weight;
107+
108+
if (nextDist < dist[next]) {
109+
//더 짧은 경로를 발견한다면 업데이트
110+
dist[next] = nextDist;
111+
pq.push([next, nextDist]);
112+
}
113+
}
114+
}
115+
}
116+
117+
dijkstra(K);
118+
119+
let answer = "";
120+
for (let i = 1; i <= V; i++) {
121+
if (dist[i] === Infinity) {
122+
answer += "INF\n";
123+
} else {
124+
answer += dist[i] + "\n";
125+
}
126+
}
127+
128+
console.log(answer);

0 commit comments

Comments
 (0)