λ¬Έμ λ§ν¬
https://www.acmicpc.net/problem/11000
μ μΆμ½λ
μΌλ¨ μμ λ€μ μμμκ°μ΄ λΉ λ₯ΈμμΌλ‘ μ λ ¬νκ³ μμμκ°μ΄ κ°μΌλ©΄ λλλ μκ°μ΄ λΉ λ₯Έμκ° μμΌλ‘ μ λ ¬νμλ€.
κ·Έλ¦¬κ³ μ λ ¬ν μμ λ€μ μννλ©΄μ μ΅μ νκ³Ό λΉκ΅νλ©΄μ(νμ μμ°κ³ μ λ ¬μ μ΄μ©νλ©΄ μ°μ°νμκ° κΈ°νκΈμμ μΌλ‘ λ§μμ μκ°μ΄κ³Όκ° λ°μνλ€.) λΉμ΄μλ κ°μμ€μ΄ μλ κ²½μ° νμ μλ‘κ² μΆκ°νμλ€. μ¬κΈ°μ μΆκ°ν λ μμ μ λλλ μκ°λ§ νμ μΆκ°νλ€. ( μ°λ¦¬κ° νμν μ 보λ μμ μ΄ λλλ μκ°μ΄κΈ° λλ¬Έμ΄λ€. )
λ§μ§λ§μ νμ μ¬μ΄μ¦λ₯Ό ν΅ν΄ λͺκ°μ κ°μμ€μ΄ μ°μλ μ§ μ μ μλ€.
μ°Έκ³ ) μλ°μ€ν¬λ¦½νΈμμλ ν μλ£κ΅¬μ‘°λ₯Ό μ§μ ꡬνν΄μΌ νλ€.
class MinHeap {
constructor() {
this.heap = [];
}
insert(v) {
let heap = this.heap;
heap.push(v);
let childIdx = heap.length - 1;
let parentIdx = parseInt((childIdx - 1) / 2);
while (childIdx >= 1 && heap[childIdx] < heap[parentIdx]) {
this.swap(parentIdx, childIdx);
childIdx = parentIdx;
parentIdx = parseInt((childIdx - 1) / 2);
}
}
replace(v) {
let heap = this.heap;
heap[0] = v;
let parentIdx = 0;
let child1Idx = 1;
let child2Idx = 2;
while (
(heap[child1Idx] !== undefined && heap[child1Idx] < heap[parentIdx]) ||
(heap[child2Idx] !== undefined && heap[child2Idx] < heap[parentIdx])
) {
if (heap[child2Idx] !== undefined) {
// child1, child2 λλ€ μλ κ²½μ°
let minIdx = heap[child1Idx] < heap[child2Idx] ? child1Idx : child2Idx;
this.swap(parentIdx, minIdx);
parentIdx = minIdx;
child1Idx = parentIdx * 2 + 1;
child2Idx = parentIdx * 2 + 2;
} else {
//child1λ§ μλ κ²½μ°
this.swap(parentIdx, child1Idx);
break;
}
}
}
swap(parentIdx, childIdx) {
let temp = this.heap[parentIdx];
this.heap[parentIdx] = this.heap[childIdx];
this.heap[childIdx] = temp;
}
getSize() {
return this.heap.length;
}
}
const inputs = require("fs")
.readFileSync(process.platform === "linux" ? "dev/stdin" : "input.txt")
.toString()
.trim()
.split("\n");
const n = +inputs[0];
const lecture = [];
for (let i = 1; i < inputs.length; i++) {
const l = inputs[i].split(" ").map((n) => Number(n));
lecture.push(l);
}
lecture.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]));
const minHeap = new MinHeap();
minHeap.insert(lecture[0][1]);
for (let i = 1; i < n; i++) {
const [start, finish] = lecture[i];
if (minHeap.heap[0] <= start) {
minHeap.replace(finish);
} else {
minHeap.insert(finish);
}
}
console.log(minHeap.getSize());
'πAlgorithm' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€[JS] > 1449λ² μ리곡 νμΉ (0) | 2024.11.04 |
---|---|
λ°±μ€[JS] > 11501λ² μ£Όμ (2) | 2024.11.04 |
λ°±μ€[JS] > 1092λ² λ°° (0) | 2024.11.02 |
λ°±μ€[JS] > 1058λ² μΉκ΅¬ (0) | 2024.10.31 |
λ°±μ€[JS] > 1051λ² μ«μ μ μ¬κ°ν (0) | 2024.10.31 |