자료구조&알고리즘
[백준]1874. 스택 수열
주멘이
2021. 1. 9. 23:26
public class p1874 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = sc.nextInt();
}
StringBuilder sb = new StringBuilder();
Stack<Integer> stack = new Stack<>();
int num = 1;
int index = 1;
while (index <= n) {
int next = arr[index];
if (stack.size() < 1) {
for (; num <= next; num++) {
stack.push(num);
sb.append('+');
}
} else {
int top = stack.peek();
if (next == top) {
stack.pop();
sb.append('-');
index++;
} else {
if (num > next) {
System.out.println("NO");
return;
}
for (; num <= next; num++) {
stack.push(num);
sb.append('+');
}
}
}
}
for (int i = 0; i < sb.length(); i++) {
System.out.println(sb.charAt(i));
}
}
}
수열이 1 2 5 3 4 인 경우
다음 수열 탐색이 3이고, 현재 오름차순 숫자가 4일 경우 pop 할 수 없으므로 NO를 출력하고 종료