티스토리 뷰
https://www.acmicpc.net/problem/23843
class MinHeap {
constructor() {
this.heap = [];
}
swap(a, b) {
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
size() {
return this.heap.length;
}
push(value) {
this.heap.push(value);
let current = this.heap.length - 1;
let parent = Math.floor((current - 1) / 2);
while (this.heap[parent] > value) {
this.swap(parent, current);
current = parent;
parent = Math.floor((current - 1) / 2);
}
}
pop() {
const last = this.heap.length - 1;
let current = 0;
this.swap(current, last); // 0번이 루트노드
const value = this.heap.pop();
while (current < last) {
let left = current * 2 + 1;
let right = current * 2 + 2;
if (left >= last) {
break;
} else if (right >= last) {
if (this.heap[current] > this.heap[left]) {
this.swap(current, left);
current = left;
} else {
break;
}
} else {
if (this.heap[left] < this.heap[current] || this.heap[right] < this.heap[current]) {
let next = this.heap[left] < this.heap[right] ? left : right;
this.swap(current, next);
current = next;
} else {
break;
}
}
}
return value;
}
}
const [[N, M], input] = require('fs')
.readFileSync('./dev/stdin')
.toString()
.trim()
.split('\n')
.map((v) => v.split(' ').map(Number));
const sorted = input.sort((a, b) => b - a);
const minheap = new MinHeap();
let index = 0;
while (index < N && index < M) {
minheap.push(sorted[index]);
index++;
}
while (index < N) {
const top = minheap.pop();
minheap.push(top + sorted[index]);
index++;
}
let answer = 0;
while (minheap.size() > 0) {
answer = minheap.pop();
}
console.log(answer);
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 22252번: 정보 상인 호석 (0) | 2023.09.07 |
---|---|
Node.js) 백준 23559번: 밥 (0) | 2023.09.07 |
Node.js) 백준 7511번: 소셜 네트워킹 어플리케이션 (0) | 2023.09.05 |
Node.js) 백준 1354번: 무한 수열 2 (0) | 2023.09.05 |
Node.js) 백준 2866번: 문자열 잘라내기 (0) | 2023.09.04 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- create databases;
- 로드나인
- DB 생성
- 다이나밍프로그래밍
- MySQL
- 그래프
- 롱베케이션
- 면접비
- 은둔청년체험
- 서버점검
- create db
- 투포인터 연습
- 투포인터
- 최소공통조상
- MOD
- 다이나믹프로그래밍
- node.js
- 동적프로그래밍
- 면접질문
- BFS
- 개발자면접
- 서버개발
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함