https://www.acmicpc.net/problem/6549
6549번: 히스토그램에서 가장 큰 직사각형
입력은 테스트 케이스 여러 개로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있고, 직사각형의 수 n이 가장 처음으로 주어진다. (1 ≤ n ≤ 100,000) 그 다음 n개의 정수 h1, ..., hn (0 ≤ hi ≤
www.acmicpc.net
얼마전에 풀었던 이 문제와 아예 똑같은 문제를 발견했다.(날로 먹었다..)
테스트 케이스가 다양해졌지만 int <-> long의 함정만 조심하면 될 것 같다.
넓이를 계산할 때 int 범위를 초과한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder result = new StringBuilder();
while (true) {
String line = br.readLine();
if (line.charAt(0) == '0') {
break;
}
String[] split = line.split(" ");
int[] histogram = new int[split.length - 1];
for (int i = 1; i < split.length; i++) {
histogram[i - 1] = Integer.parseInt(split[i]);
}
long max = 0;
Stack<int[]> left = new Stack<>();
for (int i = 0; i < histogram.length;) {
if (left.isEmpty()) {
left.push(new int[] {histogram[i], i});
i++;
}
while (i < histogram.length && left.peek()[0] <= histogram[i]) {
if (left.peek()[0] < histogram[i]) {
left.push(new int[] {histogram[i], i});
}
i++;
}
int prevIdx = 0;
int next = i < histogram.length ? histogram[i] : 0;
while (!left.isEmpty() && left.peek()[0] > next) {
int[] top = left.pop();
long height = top[0];
long width = i - top[1];
long area = height * width;
if (max < area) {
max = area;
}
prevIdx = top[1];
}
if (left.isEmpty() || left.peek()[0] < next) {
left.push(new int[] {next, prevIdx});
}
}
result.append(max).append('\n');
}
System.out.println(result);
}
}
'문제 풀이 > 백준' 카테고리의 다른 글
골드IV 공유기 설치 (0) | 2024.08.15 |
---|---|
골드III 불! (1) | 2024.08.11 |
골드V 치킨 배달 (1) | 2024.02.04 |
골드V 옥상 정원 꾸미기 (2) | 2023.06.12 |