๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/1927
๋ฌธ์ ํ์ด, ํ๊ธฐ
์ด ๋ฌธ์ ๋ ํ ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ด์ฉํด์ ์ต์ ๊ฐ์ ๊ตฌํ๋ ์ฐ์ฐ์ ์ต์ ํ ํ๋ผ๋ ๋ฌธ์ ๋ผ๊ณ ์ดํดํ๋ฉด ๋๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์์ ํ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๊ตฌํํ๊ธฐ ์ํด์๋ Class๋ฅผ ์ด์ฉํด์ ์ง์ ๊ตฌํํด์ผ ํ๋ฏ๋ก ์ง์ ๊ตฌํํ์ฌ ํ์๋ค.
์ฐธ๊ณ ๋ก ์ด๋ฐ์ ์๊ฐ์ด๊ณผ๊ฐ ๋ฌ๋๋ฐ ์๊ณ ๋ณด๋ console.log๋๋ฌธ์ด์๋ค. ๋งค๋ฒ console.log๋ฅผ ํ์ง ์๊ณ ๋ต์ ๊ตฌํ ๋ค ํ๋ฒ์ console.log๋ก ๋ต์ ์ถ๋ ฅํ๋ ์๊ฐ์ด๊ณผ๊ฐ ์ผ์ด๋์ง ์์๋ค. ์๊ฐ๋ณด๋ค console.log๊ฐ ์๊ฐ์ ๋จน๋๋ค๋ ๊ฑธ ์ ์ ์์๋ค.
heap ๊ตฌํ์ ๋ฅ์ํ์๊ธฐ ๋๋ฌธ์ ์ฝ๊ฒ ํ ์ ์์๊ณ ํ๋ฒ๋ heap์๋ฃ๊ตฌ์กฐ์ ์๊ฐ๋ณต์ก๋๋ฅผ ์ต์ ํ ํด์ฃผ๋ ํธ๋ฆฌ๊ตฌ์กฐ์ ๋ํด ์๊ฐํด๋ณด๋ ๊ณ๊ธฐ๊ฐ ๋์๋ค.
// https://www.acmicpc.net/problem/1927
// test case
// let data = "9\n0\n12345678\n1\n2\n0\n0\n0\n0\n32";
// let input = data
// .toString()
// .trim()
// .split("\n")
// .map((n) => Number(n));
let fs = require("fs");
let input = fs
.readFileSync("/dev/stdin")
.toString()
.trim()
.split("\n")
.map((n) => Number(n));
class MinHeap {
constructor() {
this.heap = [];
}
insert(n) {
let heap = this.heap;
heap.push(n);
if (heap.length >= 2) {
let childIdx = heap.length - 1;
let parentIdx = Math.floor((childIdx - 1) / 2);
while (heap[parentIdx] > heap[childIdx]) {
let [parent, child] = [heap[parentIdx], heap[childIdx]];
heap[parentIdx] = child;
heap[childIdx] = parent;
childIdx = parentIdx;
if (childIdx === 0) {
break;
}
parentIdx = Math.floor((childIdx - 1) / 2);
}
}
}
getMin() {
let heap = this.heap;
if (heap.length === 0) {
return 0;
}
let min = heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
if (heap.length > 1) {
let parentIdx = 0;
let childIdx = undefined;
if (heap[parentIdx * 2 + 2] && heap[parentIdx * 2 + 1] > heap[parentIdx * 2 + 2]) {
childIdx = parentIdx * 2 + 2;
} else if (heap[parentIdx * 2 + 1]) {
childIdx = parentIdx * 2 + 1;
}
while (heap[parentIdx] > heap[childIdx]) {
let [parent, child] = [heap[parentIdx], heap[childIdx]];
heap[parentIdx] = child;
heap[childIdx] = parent;
parentIdx = childIdx;
if (heap[parentIdx * 2 + 2] && heap[parentIdx * 2 + 1] > heap[parentIdx * 2 + 2]) {
childIdx = parentIdx * 2 + 2;
} else if (heap[parentIdx * 2 + 1]) {
childIdx = parentIdx * 2 + 1;
} else {
break;
}
}
}
return min;
}
}
let minHeap = new MinHeap();
let answer = [];
for (let i = 1; i < input.length; ++i) {
let number = input[i];
if (number === 0) {
answer.push(minHeap.getMin());
} else {
minHeap.insert(number);
}
}
console.log(answer.join("\n"));
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค[node.js] > 2805๋ฒ ๋๋ฌด ์๋ฅด๊ธฐ (1) | 2024.12.21 |
---|---|
๋ฐฑ์ค[node.js] > 2630๋ฒ ์์ข ์ด ๋ง๋ค๊ธฐ (0) | 2024.12.20 |
๋ฐฑ์ค[node.js] > 21736๋ฒ ํ๋ด๊ธฐ๋ ์น๊ตฌ๊ฐ ํ์ํด (0) | 2024.12.17 |
๋ฐฑ์ค[node.js] > 15663๋ฒ N๊ณผ M (9) (0) | 2024.12.16 |
๋ฐฑ์ค[node.js] > 11727๋ฒ 2xn ํ์ผ๋ง 2 (0) | 2024.12.15 |