Skip to content

Commit c81c344

Browse files
committed
Feat: 힙 골드 4 카드 정렬하기
1 parent f19daae commit c81c344

File tree

1 file changed

+122
-0
lines changed

1 file changed

+122
-0
lines changed

Diff for: 5주차/채수혁/골드4__카드_정렬하기.js

+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
const local_input = `
2+
4
3+
2
4+
2
5+
3
6+
3
7+
`;
8+
9+
const input = process.execArgv.includes("--stack-size=65536")
10+
? require("fs").readFileSync("dev/stdin").toString()
11+
: local_input;
12+
13+
const inputs = input
14+
.trim()
15+
.split("\n")
16+
.map((v) => Number(v));
17+
18+
const n = inputs[0];
19+
const arr = inputs.slice(1);
20+
21+
// 최소힙 구현
22+
class MinHeap {
23+
constructor() {
24+
this.heap = [];
25+
}
26+
27+
insert(value) {
28+
this.heap.push(value);
29+
this.heapifyUp();
30+
}
31+
32+
heapifyUp() {
33+
let index = this.heap.length - 1;
34+
while (index > 0) {
35+
let parentIndex = Math.floor((index - 1) / 2);
36+
37+
if (this.heap[parentIndex] <= this.heap[index]) {
38+
break;
39+
}
40+
41+
[this.heap[parentIndex], this.heap[index]] = [
42+
this.heap[index],
43+
this.heap[parentIndex],
44+
];
45+
index = parentIndex;
46+
}
47+
}
48+
49+
extractMin() {
50+
const min = this.heap[0];
51+
const ok = this.heap.pop();
52+
if (this.size() !== 0) this.heap[0] = ok;
53+
this.heapifyDown();
54+
return min;
55+
}
56+
57+
heapifyDown(index = 0) {
58+
let leftChildIndex = 2 * index + 1;
59+
let rightChildIndex = 2 * index + 2;
60+
let smallest = index;
61+
62+
if (
63+
leftChildIndex < this.heap.length &&
64+
this.heap[leftChildIndex] < this.heap[smallest]
65+
) {
66+
smallest = leftChildIndex;
67+
}
68+
69+
if (
70+
rightChildIndex < this.heap.length &&
71+
this.heap[rightChildIndex] < this.heap[smallest]
72+
) {
73+
smallest = rightChildIndex;
74+
}
75+
76+
if (smallest !== index) {
77+
[this.heap[smallest], this.heap[index]] = [
78+
this.heap[index],
79+
this.heap[smallest],
80+
];
81+
this.heapifyDown(smallest);
82+
}
83+
}
84+
size() {
85+
return this.heap.length;
86+
}
87+
peek() {
88+
return this.heap[0];
89+
}
90+
}
91+
92+
const main = () => {
93+
// n이 1이면 0을 출력하고 종료
94+
if (n === 1) {
95+
console.log(0);
96+
return;
97+
}
98+
const minHeap = new MinHeap();
99+
100+
const result = [];
101+
102+
// 최소힙에 모든 원소를 삽입
103+
arr.forEach((v) => minHeap.insert(v));
104+
105+
let prev = minHeap.extractMin() + minHeap.extractMin();
106+
result.push(prev);
107+
108+
// 힙의 크기가 1이 될 때까지 반복
109+
while (minHeap.size() > 0) {
110+
// 힙에서 가장 작은 두 개의 원소를 꺼내서 더한 후 다시 삽입
111+
minHeap.insert(prev);
112+
prev = minHeap.extractMin() + minHeap.extractMin();
113+
114+
// 더한 값을 결과 배열에 삽입
115+
result.push(prev);
116+
}
117+
118+
// 모든 원소를 더한 값을 출력
119+
console.log(result.reduce((acc, v) => acc + v, 0));
120+
};
121+
122+
main();

0 commit comments

Comments
 (0)