๐งธ์ฌ์ด ๋ฌธ์ ๋ผ๊ณ ์๊ฐํ๋๋ฐ.. ์ฒ์์๋ sort๋ฅผ ์ฌ์ฉํด์ ๊ฐ๋จํ๊ฒ ํ์๋ค. ํ์ง๋ง ํ๋ ธ๋ค๊ณ ํด์ ์ฐพ์๋ณด์๋๋ ๋๊ฐ์ง ์ฃผ์ํ ์ ์ด ์์๋ค.
๐ BigInt๋ฅผ ์จ์ผํ๋ค.
๐ ์ฐ์ ์์ ํ๋ฅผ ๊ตฌํํด์ผํ๋ค : ๋๋ ํ์ ์ฌ์ฉํด ๊ตฌํํ์๋ค.
๐จ heap ๊ตฌํ ์ฐธ๊ณ ์ฝ๋
์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [n, m] = input.shift().split(" ").map(Number);
const arr = input[0]
.split(" ")
.sort((a, b) => a - b)
.map(BigInt);
class Heap {
constructor() {
this.heap = [...arr];
}
getLeftChildIndex = (parentIndex) => parentIndex * 2 + 1;
getRightChildIndex = (parentIndex) => parentIndex * 2 + 2;
getParentIndex = (childIndex) => Math.floor((childIndex - 1) / 2);
peek = () => this.heap[0];
//์ฝ์
insert = (value) => {
const node = value;
//๋ฐฐ์ด์ ๋์ ๋ฃ๊ณ
this.heap.push(node);
//๋์ด์ฌ๋ฆฌ๊ธฐ
this.heapifyUp();
};
heapifyUp = () => {
let index = this.heap.length - 1;
const lastInsertedNode = this.heap[index];
while (index > 0) {
const parentIndex = this.getParentIndex(index);
if (this.heap[parentIndex] > lastInsertedNode) {
this.heap[index] = this.heap[parentIndex];
index = parentIndex;
} else break;
}
this.heap[index] = lastInsertedNode;
};
//์ ๊ฑฐ
remove = () => {
const count = this.heap.length;
const rootNode = this.heap[0];
if (count <= 0) return undefined;
if (count === 1) this.heap = [];
else {
this.heap[0] = this.heap.pop();
this.heapifyDown();
}
return rootNode;
};
heapifyDown = () => {
let index = 0;
const count = this.heap.length;
const rootNode = this.heap[index];
//left child๊ฐ ์์ ๋ ๊น์ง
while (this.getLeftChildIndex(index) < count) {
const leftChildIndex = this.getLeftChildIndex(index);
const rightChildIndex = this.getRightChildIndex(index);
const smallerChildIndex =
rightChildIndex < count &&
this.heap[rightChildIndex] < this.heap[leftChildIndex]
? rightChildIndex
: leftChildIndex;
if (this.heap[smallerChildIndex] <= rootNode) {
this.heap[index] = this.heap[smallerChildIndex];
index = smallerChildIndex;
} else break;
}
this.heap[index] = rootNode;
};
}
const heap = new Heap();
for (let i = 0; i < m; i++) {
const first = heap.heap[0];
heap.remove();
const second = heap.heap[0];
heap.remove();
const sum = first + second;
heap.insert(sum);
heap.insert(sum);
}
console.log(heap.heap.reduce((a, b) => a + b, 0n).toString());
์ ๋ดค์ต๋๋ค. ์ข์ ๊ธ ๊ฐ์ฌํฉ๋๋ค.