본문 바로가기
알고리즘/백준

백준 1874번 - 스택 수열 (Java 8)

by latissimus 2022. 3. 9.

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

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

        int n = Integer.parseInt(br.readLine());
        int start = 0;

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

        for(int i=0; i<n; i++){
            int targetNum = Integer.parseInt(br.readLine());

            if(targetNum > start) {
                for (int j = start + 1; j <= targetNum; j++) {
                    stack.push(j);
                    sb.append('+').append('\n');
                }
                start = targetNum;
            }
            if (targetNum <= start && targetNum != stack.peek()){
                System.out.println("NO");
                return;
            }

            stack.pop();
            sb.append('-').append('\n');
        }
        System.out.println(sb);
    }
}

 

참고 :

https://st-lab.tistory.com/182

 

[백준] 1874번 : 스택 수열 - JAVA [자바]

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,..

st-lab.tistory.com

 

'알고리즘 > 백준' 카테고리의 다른 글

백준 10845번 - 큐 (Java 8)  (0) 2022.03.10
백준 1158번 - 요세푸스 (Java 8)  (0) 2022.03.10
백준 9012번 - 괄호 (Java 8)  (0) 2022.03.08
백준 9093번 - 단어 뒤집기 (Java 8)  (0) 2022.03.08
백준 10828번 - 스택 (Java 8)  (0) 2022.03.08

댓글