티스토리 뷰

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

 

6549번: 히스토그램에서 가장 큰 직사각형

입력은 테스트 케이스 여러 개로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있고, 직사각형의 수 n이 가장 처음으로 주어진다. (1 ≤ n ≤ 100,000) 그 다음 n개의 정수 h1, ..., hn (0 ≤ hi ≤

www.acmicpc.net

 

백준 플레티넘 문제 중에서 제일 푼 사람이 많은 문제다. 

혼자 풀 수 있을 것 같은 느낌이 들어서 낑낑거리다가

최근에 다시 보니까 풀이방법이 떠올라서 도전했다가 간신히 풀었다.  알게 모르게 성장중인듯^^ 

 

 

class Item {
	prev: null | Item = null;
	constructor(public value: any) {}
}

class Stack {
	top: null | Item = null;
	size = 0;
	constructor() {}

	push(value: any) {
		const node = new Item(value);
		node.prev = this.top;
		this.top = node;
		this.size += 1;
	}

	pop() {
		if (this.top) {
			const popItem = this.top;
			this.top = this.top.prev;
			this.size -= 1;
			return popItem.value;
		} else return null;
	}

	peek() {
		return this.top ? this.top.value : null;
	}

	isEmpty() {
		return this.size == 0;
	}
}

const input: string[] = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n');
input.pop();
const answer: string[] = [];
input.map((v) => v.split(' ').map(BigInt)).forEach((arr) => {
	arr.shift();
	let max: bigint = BigInt(0);
	const st = new Stack();

	for(let i = 0; i<arr.length; i++){
		const v = arr[i];
		if(st.isEmpty()){
			if(v>max) max = v;
			st.push({ h: v, w: BigInt(1) });
		}else{
			if(v>max) max = v;
			let sz = BigInt(0);
			while(!st.isEmpty() && st.peek().h>v){
				sz = sz == BigInt(0) ? st.peek().w : sz+ st.peek().w
				const possible = st.pop().h * sz;
				if(possible>max) max = possible;
			}

			if(st.isEmpty() || st.peek().h<v){
				st.push({ h: v, w: sz+BigInt(1) });
			}else if(st.peek().h==v){
				st.peek().w += sz+BigInt(1);
			}
		}
	}
	
	let sz = BigInt(0);
	while (!st.isEmpty()) {
		sz = sz == BigInt(0) ? st.peek().w : sz+ st.peek().w
		const possible = st.pop().h * sz;
		if (possible > max) max = possible;
	}

	answer.push(max.toString());
});

console.log(answer.join('\n'));
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함