🐣 알고리즘 삐약/💻 백준 삐약

43 삐약 : 백준 2493| 탑 [바킹독 문제 풀이|스택|JAVA]

우주수첩 2023. 10. 25. 15:37
728x90

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

 

2493번: 탑

첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1

www.acmicpc.net

 

 

package BKD_0x5_Stack;

import java.io.*;
import java.util.Stack;
import java.util.StringTokenizer;


class Top{
    int num;
    int height;

    Top(int num, int height){
        this.height = height;
        this.num = num;
    }
}
public class BOJ_2493 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st ;

        int N = Integer.parseInt(br.readLine());

        Stack<Top> stack = new Stack<>();
        StringBuilder answer = new StringBuilder();
        st = new StringTokenizer(br.readLine());

        for(int i=1;i<=N;i++){
            int height = Integer.parseInt(st.nextToken());


            while (true){
                if(stack.isEmpty()){
                    answer.append("0 ");
                    stack.push(new Top(i,height));
                    break;
                }
                Top top = stack.peek();

                if(top.height > height){
                    answer.append(top.num+" ");
                    stack.push(new Top(i,height));
                    break;
                }else stack.pop();
            }

        }


        bw.write(answer.toString() + "\n");
        bw.flush();
        bw.close();
        br.close();
    }
}

 

 

참고 : https://steady-coding.tistory.com/15

 

[BOJ] 백준 2493번 : 탑 (JAVA)

 

steady-coding.tistory.com

 

 

 

 

728x90