본문 바로가기
알고리즘/문제풀이

백준 2493

by 새싹감자 2022. 8. 9.

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

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

배열로 하지말고 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;
        }
    }
  
}

'알고리즘 > 문제풀이' 카테고리의 다른 글

백준 17406  (0) 2022.08.11
sw expert 1228  (0) 2022.08.08
백준 11650 좌표 정렬하기  (0) 2022.08.03
백준 10826 피보나치 수 4  (0) 2022.08.02
백준 1929 소수 구하기  (0) 2022.08.02

댓글