728x90
스택문제입니다.
스카이라인을 통해서 빌딩의 최소 개수를 구해야합니다.
스택으로 높이에 대한 정보를 받고 더 작은 높이인경우 결과값을 +1 해주면서 pop을 합니다.
위의 과정을 반복해서 최종적으로 나온 결과를 출력해주었습니다.
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static StringTokenizer st;
static int n;
static Stack<Integer> stack;
static int result = 0;
public static void main(String[] args) throws Exception {
simulation();
}
public static void init() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
stack = new Stack<>();
}
public static void printResult() throws Exception {
bw.write(result + "");
bw.close();
}
public static void countBuilding() throws Exception {
for (int i = 0; i < n; ++i) {
st = new StringTokenizer(br.readLine());
int num = Integer.parseInt(st.nextToken());
num = Integer.parseInt(st.nextToken());
if (!stack.empty()) {
while (!stack.isEmpty() && num < stack.peek()) {
++result;
stack.pop();
}
if (!stack.empty() && num == stack.peek()) {
continue;
}
}
if (num == 0) {
continue;
}
stack.push(num);
}
while (!stack.empty()) {
++result;
stack.pop();
}
}
public static void simulation() throws Exception {
init();
countBuilding();
printResult();
}
}
'알고리즘' 카테고리의 다른 글
[Java] 프로그래머스 - 택배 배달과 수거하기 (0) | 2023.08.28 |
---|---|
[Java] 백준 2617번 구슬 찾기 (1) | 2023.08.27 |
[Java] 백준 2792번 보석 상자 (0) | 2023.08.23 |
[Java] 백준 25682번 체스판 다시 칠하기 2 (0) | 2023.08.22 |
[Java] 프로그래머스 - 여행경로 (0) | 2023.08.21 |