Problem Solving/BOJ

[Gold 3] 17299번 오등큰수

kmkunk 2022. 3. 22. 15:38
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        Stack<Integer> stack = new Stack<>();
        int n = Integer.parseInt(br.readLine());
        String[] arr = br.readLine().split(" ");
        String[] ans = new String[n];
        int[] count = new int[1000001];
        
        for(int i=0; i<n; i++) { count[Integer.parseInt(arr[i])]++; }
        
        stack.push(0); // 0 1 2 3 4
        for(int i=1; i<n; i++) { //i= 5
            while(!stack.isEmpty() &&
                count[Integer.parseInt(arr[stack.peek()])]<count[Integer.parseInt(arr[i])]) {
                    ans[stack.peek()] = String.valueOf(arr[i]);
                    stack.pop();
            }
            
            stack.push(i);
        }
        
        while(!stack.isEmpty()) { ans[stack.pop()] = "-1"; }
        
        for(String s : ans) { sb.append(s).append(" "); }
        
        System.out.println(sb);
    }
}