티스토리 뷰

https://www.acmicpc.net/problem/22252

 

22252번: 정보 상인 호석

암흑가의 권력은 주먹과 정보에서 나온다. 주먹은 한 명에게 강하고, 정보는 세계를 가지고 놀 수 있기 때문에 호석이는 세상 모든 정보를 모으는 "정보 상인"이 되고 싶다. 정보 상인은 정보를

www.acmicpc.net

class MaxHeap {
	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 [Q, ...queries] = require('fs')
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.split(' '));

const gorilla = new Map();
let cost = 0;

queries.forEach((query) => {
	const [cmd, name, ...info] = query;
	switch (cmd) {
		case '1':
			const k = +info.shift();
			const maxheap = gorilla.has(name) ? gorilla.get(name) : new MaxHeap();
			for (let i = 0; i < k; i++) {
				maxheap.push(+info[i]);
			}
			gorilla.set(name, maxheap);
			break;
		case '2':
			if (!gorilla.has(name)) break;
			const b = +info[0];
			const g = gorilla.get(name);
			for (let i = 0; i < b; i++) {
				if (g.size() == 0) {
					break;
				} else {
					cost += g.pop();
				}
			}
			break;
	}
});
console.log(cost);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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 29 30 31
글 보관함