1504번: 특정한 최단 경로
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존
www.acmicpc.net
문제
방향성이 없는 그래프가 주어진다. 세준이는 1번 정점에서 N번 정점으로 최단 거리로 이동하려고 한다. 또한 세준이는 두 가지 조건을 만족하면서 이동하는 특정한 최단 경로를 구하고 싶은데, 그것은 바로 임의로 주어진 두 정점은 반드시 통과해야 한다는 것이다.
세준이는 한번 이동했던 정점은 물론, 한번 이동했던 간선도 다시 이동할 수 있다. 하지만 반드시 최단 경로로 이동해야 한다는 사실에 주의하라. 1번 정점에서 N번 정점으로 이동할 때, 주어진 두 정점을 반드시 거치면서 최단 경로로 이동하는 프로그램을 작성하시오.
입력
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존재하며, 그 거리가 c라는 뜻이다. (1 ≤ c ≤ 1,000) 다음 줄에는 반드시 거쳐야 하는 두 개의 서로 다른 정점 번호 v1과 v2가 주어진다. (v1 ≠ v2, v1 ≠ N, v2 ≠ 1) 임의의 두 정점 u와 v사이에는 간선이 최대 1개 존재한다.
출력
첫째 줄에 두 개의 정점을 지나는 최단 경로의 길이를 출력한다. 그러한 경로가 없을 때에는 -1을 출력한다.
예제 입력 1 복사
4 6
1 2 3
2 3 3
3 4 1
1 3 5
2 4 5
1 4 4
2 3
예제 출력 1 복사
7
Solve
- 한 정점에서 다른 정점까지의 최단 경로를 구해야 하기 때문에 다익스트라 알고리즘을 사용하였습니다.
- 반드시 주어진 두개의 정점(v1, v2)를 거쳐야 하기 때문에 두가지 경우가 나올 수가 있었습니다.
- Case 1) 시작지점에서 v1을 먼저 거쳐야하는 경우 => start => v1 => v2 => end
- Case 2) 시작지점에서 v2를 먼저 거쳐야하는 경우 => start => v2 => v1 => end
- start에서 v1 혹은 v2까지의 최단거리, v1에서 v2까지의 최단거리, 그리고 마지막까지의 거리를 각각 알고리즘을 사용하여 최단거리를 구해준 후 합해줍니다. 그리고 case1 과 case2 중 더 작은 값을 답으로 출력합니다.
Code
class Node {
constructor(val, priority) {
this.val = val;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.values = [];
}
enqueue(val, priority) {
let newNode = new Node(val, priority);
this.values.push(newNode);
this.bubbleUp();
}
dequeue() {
const min = this.values[0];
const end = this.values.pop();
if (this.values.length > 0) {
this.values[0] = end;
this.bubbleDown();
}
return min;
}
bubbleUp() {
let idx = this.values.length - 1;
const element = this.values[idx];
while (idx > 0) {
let parentIdx = Math.floor((idx - 1) / 2);
let parent = this.values[parentIdx];
if (element.priority >= parent.priority) break;
this.values[parentIdx] = element;
this.values[idx] = parent;
idx = parentIdx;
}
}
bubbleDown() {
let idx = 0;
const length = this.values.length;
const element = this.values[0];
while (true) {
let leftChildIdx = 2 * idx + 1;
let rightChildIdx = 2 * idx + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIdx < length) {
leftChild = this.values[leftChildIdx];
if (leftChild.priority < element.priority) {
swap = leftChildIdx;
}
}
if (rightChildIdx < length) {
rightChild = this.values[rightChildIdx];
if (
(swap === null && rightChild.priority < element.priority) ||
(swap !== null && rightChild.priority < leftChild.priority)
) {
swap = rightChildIdx;
}
}
if (swap === null) break;
this.values[idx] = this.values[swap];
this.values[swap] = element;
idx = swap;
}
}
}
const input = require("fs").readFileSync("/dev/stdin").toString().trim().split("\n");
const arr = input.map(el=>el.split(' ').map(el=>+el));
const [n, e] = arr.shift();
const [v1, v2] = arr.pop();
const graph = {};
let answer = 0;
for(let i = 1; i <= n; i++) {
graph[i] = [];
}
for(let i = 0 ; i < e; i++) {
const [s, e, w] = arr[i];
graph[s].push([e, w]);
graph[e].push([s, w]);
}
const dijkstra = (start, end) => {
const distances = Array.from({length:n+1}, ()=> 0);
const initDistance = () => {
for(let i = 0 ; i <= n; i++) {
distances[i] = Infinity;
}
}
initDistance();
const q = new PriorityQueue();
distances[start] = 0;
q.enqueue([start, 0],0);
while(q.values.length) {
const [nowNode, nowDist] = q.dequeue().val;
if(nowNode === end) break;
for(let x of graph[nowNode]) {
const [nextNode, nextDist] = x;
if(nowDist + nextDist < distances[nextNode]) {
distances[nextNode] = nowDist + nextDist;
q.enqueue([nextNode, distances[nextNode]], distances[nextNode]);
}
}
}
return distances[end];
}
answer = Math.min(dijkstra(1, v1) + dijkstra(v1, v2) + dijkstra(v2, n),
dijkstra(1, v2) + dijkstra(v2, v1) + dijkstra(v1, n));
console.log(answer === Infinity ? -1 : answer);
'BOJ > Node.js' 카테고리의 다른 글
[BOJ / Node.js] 1987. 알파벳 (0) | 2023.04.03 |
---|---|
[BOJ / Node.js] 2668. 숫자고르기 (0) | 2023.04.02 |
[BOJ / Node.js] 1916. 최소비용 구하기 (0) | 2023.03.31 |
[BOJ / Node.js] 11000. 강의실 배정 (0) | 2023.03.30 |
[BOJ / Node.js] 1715. 카드 정렬하기 (0) | 2023.03.29 |