💡Problem Solving/BOJ

[BOJ 1874] 스택 수열 (Java)

gom20 2021. 10. 17. 16:56

#문제

https://www.acmicpc.net/problem/1874

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

#소스코드

package stack;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class BOJ1874 {

    public static int N;
    public static Queue<Integer> que;

    public static void input() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        que = new LinkedList<Integer>();
        for(int i = 1; i <= N; i++){
            que.offer(Integer.parseInt(br.readLine()));
        }
    }

    public static void main(String[] args) throws Exception {
        input();
        StringBuilder sb = new StringBuilder();
        Stack<Integer> st = new Stack<Integer>();
        for(int i = 1; i <= N; i++){
            st.push(i);
            sb.append("+\n");

            while(!st.isEmpty() && st.peek().intValue() == que.peek().intValue()){
                que.poll();
                st.pop();
                sb.append("-\n");
            }
        }

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        if(que.size() > 0){
            bw.write("NO");
        } else {
            bw.write(sb.toString());
        }
        bw.flush();
    }
}