새싹감자 2022. 8. 9. 09:35

문제를 스택으로 푸는 이유!

->시간초과때문에 스택으로 쓴다

배열로 하지말고 stringbuilder로 해야되지 않을까..?

->근데 얘 거꾸로 쌓임

->뒤에서부터 오지말고 앞에서부터 넣으면 어때?

->스택을 사용하자!

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;


public class Main {
  
    public static void main(String[] args) throws Exception{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Stack<Tower> stack = new Stack<Tower>();
        int height, position;
        int N = Integer.parseInt(br.readLine()); 
          
        StringTokenizer st = new StringTokenizer(br.readLine());
        for (position=1; position<=N; position++) {
            height = Integer.parseInt(st.nextToken()); 
          
            while(!stack.isEmpty()) {  
                if(stack.peek().height >= height) {
                    System.out.print(stack.peek().position + " ");
                    break;
                }
                stack.pop(); 
            }
            if(stack.isEmpty())
                System.out.print(0 + " ");
            stack.push(new Tower(height, position));
        }
          
          
        br.close();
    }
    
    static class Tower {
        int height;    
        int position;       
          
        public Tower(int height, int position) {
            this.height = height;
            this.position = position;
        }
    }
  
}