20250905 baekjoon
This commit is contained in:
parent
b522aca1c0
commit
82c13c54fd
83
code_study/Baekjoon/ts/1916.ts
Normal file
83
code_study/Baekjoon/ts/1916.ts
Normal file
@ -0,0 +1,83 @@
|
||||
export {};
|
||||
|
||||
class PriorityQueue {
|
||||
private heap: number[][];
|
||||
|
||||
constructor() {
|
||||
this.heap = [];
|
||||
}
|
||||
|
||||
isEmpty(): boolean {
|
||||
return this.heap.length === 0;
|
||||
}
|
||||
|
||||
push(node: number[]) {
|
||||
this.heap.push(node);
|
||||
let index = this.heap.length - 1;
|
||||
while (index > 0) {
|
||||
const parentIndex: number = Math.floor((index - 1) / 2);
|
||||
if (this.heap[parentIndex][1] <= this.heap[index][1]) break;
|
||||
|
||||
[this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
|
||||
index = parentIndex;
|
||||
}
|
||||
}
|
||||
|
||||
pop(): number[] {
|
||||
if (this.isEmpty()) return [-1,-1];
|
||||
|
||||
const root: number[] = this.heap[0];
|
||||
const lastNode = this.heap.pop();
|
||||
|
||||
if (!this.isEmpty()) {
|
||||
this.heap[0] = lastNode;
|
||||
let index: number = 0;
|
||||
const length: number = this.heap.length;
|
||||
|
||||
while (true) {
|
||||
let smallest: number = index;
|
||||
const leftChildIndex: number = 2 * index + 1;
|
||||
const rightChildIndex: number = 2 * index + 2;
|
||||
|
||||
if (leftChildIndex < length && this.heap[leftChildIndex][1] < this.heap[smallest][1]) smallest = leftChildIndex;
|
||||
if (rightChildIndex < length && this.heap[rightChildIndex][1] < this.heap[smallest][1]) smallest = rightChildIndex;
|
||||
if (smallest === index) break;
|
||||
|
||||
[this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
|
||||
index = smallest;
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
const input: string[] = require("fs").readFileSync(0, "utf8").toString().trim().split('\n');
|
||||
const [N, M]: number[] = [input[0], input[1]].map(Number);
|
||||
let adj: number[][][] = Array.from({length: N+1}, () => []);
|
||||
|
||||
for(let i=0; i<M; i++) {
|
||||
const [u,v,w]: number[] = input[2+i].split(" ").map(Number);
|
||||
adj[u].push([v,w]);
|
||||
}
|
||||
|
||||
const [u, v]: number[] = input[M+2].split(" ").map(Number);
|
||||
let distance: number[] = new Array(N+1).fill(Infinity);
|
||||
distance[u] = 0;
|
||||
const pq = new PriorityQueue();
|
||||
pq.push([u,0]);
|
||||
|
||||
while(!pq.isEmpty()) {
|
||||
const [current, cw]: number[] = pq.pop();
|
||||
|
||||
if(distance[current] < cw) continue;
|
||||
|
||||
for(let [next, nw] of adj[current]) {
|
||||
if(distance[next] > distance[current] + nw) {
|
||||
distance[next] = distance[current] + nw;
|
||||
pq.push([next, distance[next]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(distance[v]);
|
||||
Loading…
x
Reference in New Issue
Block a user