이론/Data Structure , Algorithm
[210916] 백준 1874번 문제 풀이 / 스택 수열
6161990
2021. 9. 16. 20:01
문제의 핵心
1. 스택에 원소를 삽입할 때는, 단순히 특정 수에 도달할 때까지 삽입한다.
2. 스택에서 원소를 연달아 빼낼 때 내림차순을 유지할 수 있는지 확인한다.
import java.util.Scanner;
import java.util.Stack;
public class Q3_1874 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
Stack<Integer> stack = new Stack<>();
int N = sc.nextInt();
int count = 1;
while(N --> 0) {
int value = sc.nextInt();
while(count <= value) {
stack.push(count);
count += 1;
sb.append('+').append('\n');
}
if(stack.peek() == value) {
stack.pop();
sb.append('-').append('\n');
}else {
System.out.println("NO");
System.exit(0);
}
}
System.out.println(sb);
}
}