class Node {
constructor(to, weight) {
this
.to = to;
this
.weight = weight;
}
}
function
minTime(graph, n, k) {
const adj =
new
Array(n + 1);
for
(let i = 0; i <= n; i++) {
adj[i] = [];
}
for
(const edge of graph) {
const from = edge[0];
const to = edge[1];
const weight = edge[2];
adj[from].push(
new
Node(to, weight));
}
const minH =
new
PriorityQueue((a, b) => a[0] - b[0]);
const dist =
new
Array(n + 1).fill(Infinity);
minH.enqueue([0, k]);
dist[k] = 0;
while
(!minH.isEmpty()) {
const [currDist, currNode] = minH.dequeue();
for
(const child of adj[currNode]) {
const childNode = child.to;
const childDist = child.weight;
if
(currDist + childDist < dist[childNode]) {
dist[childNode] = currDist + childDist;
minH.enqueue([dist[childNode], childNode]);
}
}
}
let maxx = -Infinity;
for
(let i = 1; i <= n; i++) {
maxx = Math.max(maxx, dist[i]);
}
if
(maxx === Infinity) {
return
-1;
}
return
maxx;
}
class PriorityQueue {
constructor(compareFn) {
this
.elements = [];
this
.compare = compareFn;
}
enqueue(element) {
this
.elements.push(element);
this
.bubbleUp();
}
dequeue() {
if
(
this
.isEmpty()) {
return
undefined;
}
const root =
this
.elements[0];
const last =
this
.elements.pop();
if
(!
this
.isEmpty()) {
this
.elements[0] = last;
this
.sinkDown();
}
return
root;
}
isEmpty() {
return
this
.elements.length === 0;
}
bubbleUp() {
let index =
this
.elements.length - 1;
while
(index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if
(
this
.compare(
this
.elements[index],
this
.elements[parentIndex]) >= 0) {
break
;
}
this
.swap(index, parentIndex);
index = parentIndex;
}
}
sinkDown() {
let index = 0;
const length =
this
.elements.length;
while
(
true
) {
const leftChildIdx = 2 * index + 1;
const rightChildIdx = 2 * index + 2;
let smallest = index;
if
(leftChildIdx < length &&
this
.compare(
this
.elements[leftChildIdx],
this
.elements[smallest]) < 0) {
smallest = leftChildIdx;
}
if
(rightChildIdx < length &&
this
.compare(
this
.elements[rightChildIdx],
this
.elements[smallest]) < 0) {
smallest = rightChildIdx;
}
if
(smallest === index) {
break
;
}
this
.swap(index, smallest);
index = smallest;
}
}
swap(i, j) {
[
this
.elements[i],
this
.elements[j]] = [
this
.elements[j],
this
.elements[i]];
}
}
const graph = [
[2, 1, 1],
[2, 3, 1],
[3, 4, 1]
];
const n = 4;
const k = 2;
const result = minTime(graph, n, k);
if
(result === -1) {
console.log(
"It's impossible to infect all nodes."
);
}
else
{
console.log(
"Minimum time to infect all nodes: "
+ result);
}