Skip to content

Commit 456f987

Browse files
author
Eric
committed
118차 2번 문제풀이
1 parent 02fc44d commit 456f987

1 file changed

Lines changed: 94 additions & 0 deletions

File tree

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
class MinHeap {
2+
constructor() {
3+
this.heap = [];
4+
}
5+
push(value) {
6+
this.heap.push(value);
7+
this.bubbleUp();
8+
}
9+
10+
pop() {
11+
if (this.heap.length === 1) return this.heap.pop();
12+
const min = this.heap[0];
13+
this.heap[0] = this.heap.pop();
14+
this.bubbleDown();
15+
return min;
16+
}
17+
18+
bubbleUp() {
19+
let index = this.heap.length - 1;
20+
21+
while (index > 0) {
22+
const parentIndex = Math.floor((index - 1) / 2);
23+
if (this.heap[parentIndex] <= this.heap[index]) break;
24+
[this.heap[parentIndex], this.heap[index]] = [
25+
this.heap[index],
26+
this.heap[parentIndex],
27+
];
28+
index = parentIndex;
29+
}
30+
}
31+
32+
bubbleDown() {
33+
let index = 0;
34+
const length = this.heap.length;
35+
36+
while (true) {
37+
const left = 2 * index + 1;
38+
const right = 2 * index + 2;
39+
let smallest = index;
40+
41+
if (left < length && this.heap[left] < this.heap[smallest]) {
42+
smallest = left;
43+
}
44+
45+
if (right < length && this.heap[right] < this.heap[smallest]) {
46+
smallest = right;
47+
}
48+
49+
if (smallest === index) break;
50+
51+
[this.heap[index], this.heap[smallest]] = [
52+
this.heap[smallest],
53+
this.heap[index],
54+
];
55+
56+
index = smallest;
57+
}
58+
}
59+
60+
least() {
61+
return this.heap[0];
62+
}
63+
64+
size() {
65+
return this.heap.length;
66+
}
67+
}
68+
69+
const input = require('fs')
70+
.readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
71+
.toString()
72+
.trim()
73+
.split('\n')
74+
.map(Number);
75+
76+
function solution(input) {
77+
const N = input[0];
78+
const cards = input.slice(1).map(Number);
79+
const minHeap = new MinHeap();
80+
for (let i = 0; i < N; i++) {
81+
minHeap.push(cards[i]);
82+
}
83+
84+
let sum = 0;
85+
while (minHeap.size() > 1) {
86+
const a = minHeap.pop();
87+
const b = minHeap.pop();
88+
sum += a + b;
89+
minHeap.push(a + b);
90+
}
91+
return sum;
92+
}
93+
94+
console.log(solution(input));

0 commit comments

Comments
 (0)