๐ŸŽฒ ๋ฐฑ์ค€ 15903๋ฒˆ ์นด๋“œ ํ•ฉ์ฒด ๋†€์ด

Jeongeunยท2023๋…„ 8์›” 2์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
103/186

๋ฐฑ์ค€ 15903๋ฒˆ

๐Ÿงธ์‰ฌ์šด ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ.. ์ฒ˜์Œ์—๋Š” 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());

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2023๋…„ 8์›” 2์ผ

์ž˜ ๋ดค์Šต๋‹ˆ๋‹ค. ์ข‹์€ ๊ธ€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ