알고리즘 풀이/백준

[백준][Java] 2493번 탑

배게 2019. 12. 11. 03:06
728x90



메모리초과 -BufferedReader


프로그래머스랑 똑같은 문제인데 프로그래머스에서는 최대 탑 개수가 100개임 (이중 for문으로도 뚝딱)


N의 개수로 시간초과, 메모리 초과를 조절해주어야하는 문제임. 


for문 만드는 것은 


스택이 비어있을 경우를 생각하고 


while문을 활용해 신규 탑보다 작은 모든 값을 popping 시켜줌


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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
 
public class Problem191210_10 {
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        
        Scanner sc = new Scanner(System.in);
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        
        
        int N = Integer.parseInt(bf.readLine());
        
        int[] height = new int[N];
        int[] answer = new int[N];
        
        Stack<TopInfo> st = new Stack<>();
        
        StringTokenizer stn = new StringTokenizer(bf.readLine());
        for(int i=0; i<N; i++) {
            height[i] = Integer.parseInt(stn.nextToken());
        }
        
        for(int i=N-1; i>=0; i--) {
            TopInfo t = new TopInfo(i, height[i]);
            if(!st.isEmpty()) {
                while(!st.isEmpty()) {
                    if(st.peek().height>=t.height) {
                        break;
                    }
                    else {
                        answer[st.pop().index] = i+1;
                    }                
                }
                st.push(t);
            }
            else st.push(t);
            
        }
        
        for(int i : answer) {
            System.out.print(i+" ");
        }
        
        
    }
    
    static class TopInfo{
        int index;
        int height;
        
        TopInfo(int index, int height) {
            this.index = index;
            this.height = height;
        }
        
    }
    
}
cs