[다익스트라] 최소비용 구하기2 (11779)
문제 설명
n(1≤n≤1,000)개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 m(1≤m≤100,000)개의 버스가 있다.
우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다.
그러면 A번째 도시에서 B번째 도시 까지 가는데 드는 최소비용과 경로를 출력하여라.
항상 시작점에서 도착점으로의 경로가 존재한다.
입력
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다.
그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다.
먼저 처음에는 그 버스의 출발 도시의 번호가 주어진다. 그리고 그 다음에는 도착지의 도시 번호가 주어지고 또 그 버스 비용이 주어진다.
버스 비용은 0보다 크거나 같고, 100,000보다 작은 정수이다.
그리고 m+3째 줄에는 우리가 구하고자 하는 구간 출발점의 도시번호와 도착점의 도시번호가 주어진다.
출력
첫째 줄에 출발 도시에서 도착 도시까지 가는데 드는 최소 비용을 출력한다.
둘째 줄에는 그러한 최소 비용을 갖는 경로에 포함되어있는 도시의 개수를 출력한다. 출발 도시와 도착 도시도 포함한다.
셋째 줄에는 최소 비용을 갖는 경로를 방문하는 도시 순서대로 출력한다.
🔍 문제 풀이
다익스트라 알고리즘을 이용해서 출발 도시에서 도착 도시까지의 최소비용을 구할 수 있다.
힙에 경로를 넣어줄 때에 해당 노드의 경로는 갱신해주면 된다.
import heapq
import sys
input = sys.stdin.readline
N = int(input())
M = int(input())
INF = int(1e9)
graph = [[]for i in range(N+1)]
distance = [INF] * (N+1) # 최소 거리 저장
path = [[] for _ in range(N+1)] # 경로 저장
for _ in range(M):
s, e, c = map(int, input().split())
graph[s].append((e,c))
FROM, TO = map(int, input().split()) #시작/끝 노드
path[FROM].append(FROM) # 시작 노드의 경로에는 반드시 자신을 포함함
def dijkstra(start):
q=[]
heapq.heappush(q, (0,start))
distance[start] = 0
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(q,(cost, i[0]))
path[i[0]] = [] # 탐색한 노드의 경로 초기화
for p in path[now]: # 이전 노드의 내용 복사
path[i[0]].append(p)
path[i[0]].append(i[0]) # 자신 추가
dijkstra(FROM)
print(distance[TO])
print(len(path[TO]))
print(' '.join(map(str,path[TO])))
자바스크립트는 힙 라이브러리가 없기 때문에 직접 구현해야 한다.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// 최소 힙
class Heap {
constructor() {
this.heap = [null];
}
swap(a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
//삽입: 배열 마지막에 삽입 후 부모 노드와 비교하여 재정렬
heappush(value) {
this.heap.push(value);
let curIndx = this.heap.length - 1;
let parIndx = (curIndx / 2) >> 0;
while (curIndx > 1 && this.heap[parIndx] > this.heap[curIndx]) {
this.swap(parIndx, curIndx);
curIndx = parIndx;
parIndx = (curIndx / 2) >> 0;
}
}
//삭제: 배열의 첫번째 값pop, 가장 마지막 값을 루트로 가져온 후 자식노드와 비교하여 재정렬
heappop() {
const min = this.heap[1];
if (this.heap.length <= 2) this.heap = [null];
else {
this.heap[1] = this.heap.pop();
}
let curIndx = 1;
let leftIndx = curIndx * 2;
let rightIndx = curIndx * 2 + 1;
if (!this.heap[leftIndx]) return min; //왼쪽 자식이 없다면 오른쪽도 없다(자식이 없는 경우)
if (!this.heap[rightIndx]) { // 왼쪽 자식노드만 있는 경우
if (this.heap[leftIndx] < this.heap[curIndx]) {
this.swap(leftIndx, curIndx);
}
return min;
}
// 왼쪽,오른쪽 자식노드가 다 있을 경우
while (
this.heap[leftIndx] < this.heap[curIndx] ||
this.heap[rightIndx] < this.heap[curIndx]
) {
const minIndx = this.heap[leftIndx] < this.heap[rightIndx] ? leftIndx : rightIndx;
this.swap(minIndx, curIndx);
curIndx = minIndx;
leftIndx = curIndx * 2;
rightIndx = curIndx * 2 + 1;
}
return min;
}
}
const dijkstra = (start, distance, graph, path) => {
const myHeap = new Heap();
myHeap.heappush([0, start]);
distance[start] = 0;
while (myHeap.heap.length > 1) {
let [dist, now] = myHeap.heappop();
if (distance[now] < dist) {
continue;
}
for (const i of graph[now]) {
const cost = dist + parseInt(i[1]);
if (distance[i[0]] > cost) {
distance[i[0]] = cost;
myHeap.heappush([cost, i[0]]);
path[i[0]] = [];
for (const p of path[now]) {
path[i[0]].push(p);
}
path[i[0]].push(i[0]);
}
}
}
};
const solution = (arr) => {
let graph = Array.from({ length: n + 1 }, () => []);
let path = Array.from({ length: n + 1 }, () => []);
let distance = Array.from({ length: n + 1 }, () => Infinity);
for (let i = 0; i < m; i++) {
let [s, e, c] = [arr[i][0], arr[i][1], arr[i][2]];
graph[s].push([e, c]);
}
path[from].push(from);
dijkstra(from, distance, graph, path);
console.log(path);
console.log(distance[to]);
console.log(path[to].length);
console.log(path[to].map((e) => parseInt(e)).join(" "));
};
// == 메인 == //
let [n, m] = [null, null];
let data = [];
let [from, to] = [0, 0];
rl.on("line", function (line) {
if (!n) {
n = +line;
} else if (!m) {
m = +line;
} else {
data.push(line.split(" "));
}
if (data.length > m) {
const info = line.split(" ");
[from, to] = [info[0], info[1]];
solution(data);
rl.close();
}
}).on("close", function () {
process.exit();
});
😀 후기
자바스크립트로 힙 구현하려니깐.. 좀 길어졌다. 파이썬의 간결함을 다시 한번 느꼈다 :)
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net