Algorithm

[BOJ] 2493. 탑

프로그래민 2020. 4. 7. 11:57
반응형

스택을 이용하여 비교하는 문제이다.

탑의 첫번째 부터 확인하며 스택이 비어있다면 0(벽), 만일 스택이 안비어있다면 스택의 top이 현재보다 크다면 top의 인덱스 출력 그렇지 않다면 top을 pop해주는 것을 반복해주며 최종적으로는 push를 계속 해주는 과정을 반복해주었다. 로직을 천천히 생각해봐야할 필요가 있는 문제였다.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package selfStudy.chap04;
 
 
public class Main_bj_2493_탑 {
 
    static class Tower{
        int index;
        long height;
 
        Tower(int index,long height){
            this.index=index;
            this.height=height;
        }
    }
 
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N= Integer.parseInt(br.readLine());
 
        Stack<Tower> stack = new Stack<>();
 
        StringTokenizer st = new StringTokenizer(br.readLine());
        StringBuilder sb = new StringBuilder();
 
        for(int i=1;i<=N;i++) {
            long height= Long.parseLong(st.nextToken());
 
            while(!stack.isEmpty()) {
                if(stack.peek().height>=height) {        //스택탑이 현재보다 크다면
                    sb.append(stack.peek().index+" ");
                    break;
                }else {    //현재가 스택탑보다 크다면
                    stack.pop();
                }
            }
            if(stack.isEmpty()) {
                sb.append("0 ");            
            }
            stack.push(new Tower(i,height));
 
        }
        System.out.println(sb.toString());
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
                                                  
반응형

'Algorithm' 카테고리의 다른 글

[BOJ] 10971. 외판원 순회2  (0) 2020.04.08
[BOJ] 10974. 모든 순열  (0) 2020.04.07
[BOJ] 11559. Puyo Puyo  (0) 2020.04.06
[BOJ] 6588. 골드바흐의 추측  (0) 2020.04.04
[SWEA] 5607. 조합  (0) 2020.04.03