티스토리 뷰

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

 

28703번: Double It

 $31$에 $2$를 곱해서 $62$로, $41$에 $2$를 곱해서 $82$로, $51$ 에 $2$를 곱해서 $102$로, $3$에 $2$를 $5$번 곱해서 $96$으로 만들면, $A$의 최댓값 $102$와 최솟값 $62$의 차이가 $40$으로 최소가 됩니다.

www.acmicpc.net

 

 

 

 

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, arr] = require('fs')
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.split(' ').map(Number));

const minHeap = new MinHeap();
let max = 0;

let answer = Infinity;
for (let i = 0; i < arr.length; i++) {
	max = arr[i] > max ? arr[i] : max;
	minHeap.push(arr[i]);
}

const originMax = max;
while (true) {
	const min = minHeap.pop();
	if (min > originMax) break;
	const diff = max - min;
	if (diff < answer) answer = diff;
	let duobleMin = min * 2;
	if (duobleMin > max) max = duobleMin;
	minHeap.push(duobleMin);
}
console.log(answer);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
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
글 보관함