최소 힙 사용(JS) 백준 1715

Mayton·2022년 1월 31일
0

Coding-Test

목록 보기
1/37
post-thumbnail

1715번 백준

1715 번을 다음과 같이 문제를 해결했을 때는 시간이 오래걸려 통과 되지 못했다.

//가장 작은것을 두개 뽑아서 합친뒤에 array에 다시 넣고, 만약 하나만 남으면 그걸 console.log 한다
const fs = require('fs');
const [n, ...arr] = fs
  .readFileSync('./data')
  .toString()
  .trim()
  .split('\n')
  .map((v) => v * 1);

let resultOne = 0;
while (arr.length > 1) {
  arr.sort((a, b) => b - a);
  const one = arr.pop();
  const two = arr.pop();
  const compareOne = one + two;
  resultOne += compareOne;
  arr.push(compareOne);
}
console.log(resultOne);

그래서 최소 힙 방식을 공부, 및 사용하였고, 통과할 수 있었다.
만약 파이썬을 사용한 다면 기본 라이브러리 사용을 통해 해결할 수 있지만, JS를 통한 코드테스트를 준비하고 있는 입장에서 최소힙 라이브러리를 깃에 올려두고 구현하는 방식을 지속해서 연습하고, 구현할 수 있도록 해야겠다.
참고한 사이트

function MinHeap() {
  this.heap = [0];
  this.insert = (v) => {
    this.heap.push(v);
    let p = this.heap.length - 1;
    while (p > 1 && this.heap[Math.floor(p / 2)] > this.heap[p]) {
      let tmp = this.heap[Math.floor(p / 2)];
      this.heap[Math.floor(p / 2)] = this.heap[p];
      this.heap[p] = tmp;
      p = Math.floor(p / 2);
    }
  };
  this.getLength = () => {
    return this.heap.length;
  };
  this.delete = () => {
    if (this.heap.length - 1 < 1) {
      return 0;
    }
    let deletedItem = this.heap[1];
    this.heap[1] = this.heap[this.heap.length - 1];
    this.heap.pop();
    let p = 1;
    while (p * 2 < this.heap.length) {
      let min = this.heap[p * 2];
      let minP = p * 2;
      if (p * 2 + 1 < this.heap.length && min > this.heap[p * 2 + 1]) {
        min = this.heap[p * 2 + 1];
        minP = p * 2 + 1;
      }
      if (this.heap[p] < min) {
        break;
      }
      let tmp = this.heap[p];
      this.heap[p] = this.heap[minP];
      this.heap[minP] = tmp;
      p = minP;
    }
    return deletedItem;
  };
}

const solution = (n, list) => {
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    let card1 = list.delete();
    let card2 = list.delete();

    let sum = card1 + card2;
    cnt += sum;

    list.insert(sum);
  }
  console.log(cnt);
};

const fs = require('fs');
const [n, ...input] = fs
  .readFileSync('./data')
  .toString()
  .trim()
  .split('\n')
  .map((v) => v * 1);

let list = new MinHeap();
for (let i = 0; i < n; i++) {
  let tmp = Number(input.shift());
  list.insert(tmp);
}

solution(n, list);
profile
개발 취준생

0개의 댓글