function
kSmallestPair(A, B, K) {
const n = A.length;
const pq =
new
PriorityQueue((a, b) => a[0] < b[0]);
const mySet =
new
Set();
pq.enqueue([A[0] + B[0], [0, 0]]);
mySet.add([0, 0].toString());
let flag = 1;
for
(let count = 0; count < K && flag; count++) {
const [sum, [i, j]] = pq.dequeue();
console.log(`(${A[i]}, ${B[j]})`);
flag = 0;
if
(i + 1 < A.length) {
const nextSum = A[i + 1] + B[j];
const key = [i + 1, j].toString();
if
(!mySet.has(key)) {
pq.enqueue([nextSum, [i + 1, j]]);
mySet.add(key);
}
flag = 1;
}
if
(j + 1 < B.length) {
const nextSum = A[i] + B[j + 1];
const key = [i, j + 1].toString();
if
(!mySet.has(key)) {
pq.enqueue([nextSum, [i, j + 1]]);
mySet.add(key);
}
flag = 1;
}
}
}
class PriorityQueue {
constructor(comparator) {
this
.heap = [];
this
.comparator = comparator || ((a, b) => a < b);
}
enqueue(value) {
this
.heap.push(value);
this
.bubbleUp();
}
dequeue() {
const root =
this
.heap[0];
const last =
this
.heap.pop();
if
(
this
.heap.length > 0) {
this
.heap[0] = last;
this
.sinkDown();
}
return
root;
}
bubbleUp() {
let index =
this
.heap.length - 1;
while
(index > 0) {
const current =
this
.heap[index];
const parentIndex = Math.floor((index - 1) / 2);
const parent =
this
.heap[parentIndex];
if
(
this
.comparator(current, parent)) {
break
;
}
this
.heap[index] = parent;
this
.heap[parentIndex] = current;
index = parentIndex;
}
}
sinkDown() {
let index = 0;
const length =
this
.heap.length;
const current =
this
.heap[0];
while
(
true
) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let leftChild, rightChild;
let swap =
null
;
if
(leftChildIndex < length) {
leftChild =
this
.heap[leftChildIndex];
if
(
this
.comparator(leftChild, current)) {
swap = leftChildIndex;
}
}
if
(rightChildIndex < length) {
rightChild =
this
.heap[rightChildIndex];
if
(
(swap ===
null
&&
this
.comparator(rightChild, current)) ||
(swap !==
null
&&
this
.comparator(rightChild, leftChild))
) {
swap = rightChildIndex;
}
}
if
(swap ===
null
) {
break
;
}
this
.heap[index] =
this
.heap[swap];
this
.heap[swap] = current;
index = swap;
}
}
}
const A = [1];
const B = [2, 4, 5, 9];
const K = 8;
kSmallestPair(A, B, K);