πŸ—οΈ Algorithm/🟩 λ°±μ€€

🟩 [λ°±μ€€] [Java] [Silver2] 1874번_μŠ€νƒ μˆ˜μ—΄

Dbswnstjd 2024. 1. 13. 17:45

문제

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

풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class μŠ€νƒμˆ˜μ—΄ {
    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());

        int start = 0;

        while(n-- > 0){
            int value = Integer.parseInt(br.readLine());

            if(value > start){
                for(int i=start+1; i<=value; i++){
                    stack.push(i);
                    sb.append('+').append('\n');
                }
                start = value;
            }

            else if(stack.peek() != value){
                System.out.println("NO");
                return;
            }

            stack.pop();
            sb.append("-").append("\n");
        }

        System.out.println(sb);
    }
}