문제 제목 : 스택 수열
난이도 : 하
문제 유형 : 스택, 그리디
추천 풀이 시간 : 30분 (못하면 2배 60분)
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.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Character> result = new ArrayList<>();
int n = Integer.parseInt(br.readLine());
Stack<Integer> stack = new Stack<>();
int num = 1;
for (int i = 0; i < n; i++) {
int data = Integer.parseInt(br.readLine());
while (num <= data) {
stack.push(num++);
result.add('+');
}
if (stack.peek() == data) {
stack.pop();
result.add('-');
} else {
System.out.println("NO");
return;
}
}
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
}
'Algorithm > BAEKJOON' 카테고리의 다른 글
[알고리즘-DP] 파도반 수열 (0) | 2023.01.20 |
---|---|
[알고리즘-DP] 2×n 타일링 (0) | 2023.01.20 |
[자료구조-큐] 프린터 큐 (0) | 2023.01.20 |
[자료구조-배열] 블랙잭 (0) | 2023.01.19 |
[자료구조-배열] 음계 (0) | 2023.01.19 |