Algorithm/baekjoon

스택 수열

마닐라 2022. 3. 2. 14:28

📍 문제 설명

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.*;

public class Main {
    static int n, m, v, e, k, r, answer, cnt, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE, firstX, firstY;
    static int[] arr, dx = {1,0,-1,0}, dy = {0,-1,0,1};
    static long[] dp;
    static char[][] board, clone;
    static boolean[][] visited;
    static ArrayList<Integer> list;
    static TreeSet<Character> set;
    static StringBuilder sb;
    static StringTokenizer st;

    public static void main(String[] args) throws IOException {
        Main T = new Main();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());
        arr = new int[n];
        for(int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(br.readLine());
        }

        Stack<Integer> s = new Stack<>();
        sb = new StringBuilder();

        int index = 0;
        int num = 1;
        while(num <= n) {
            s.push(num++);
            sb.append('+').append("\n");
            //현재 꼭대기 값이 수열의 원소면 pop 시켜주기
            while(!s.isEmpty() && s.peek() == arr[index]) {
                s.pop();
                sb.append('-').append("\n");
                index++;
            }
        }
        if(index == n) System.out.println(sb);
        else System.out.println("NO");
    }

    private void solution() {

    }


}

'Algorithm > baekjoon' 카테고리의 다른 글

기적의 매매법  (0) 2022.03.03
상어 초등학교  (0) 2022.03.02
Two Dots=========  (0) 2022.03.02
2048  (0) 2022.03.01
가르침  (0) 2022.03.01