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
알고리즘 분류
public class StackSequence_1874 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayDeque<Integer> arr = new ArrayDeque<Integer>();
ArrayDeque<String> output = new ArrayDeque<String>();
int inputCnt = Integer.parseInt(br.readLine());
int max = 0;
for (int i = 0; i < inputCnt; i++) {
int target = Integer.parseInt(br.readLine());
if(arr.contains(target)) {
if(arr.peekLast() == target) {
arr.removeLast();
output.addLast("-");
if(arr.isEmpty()) continue;
}else {
output.addLast("no");
}
}else {
int moveCnt = target - max;
for (int j = 0; j < moveCnt; j++) {
arr.addLast(max+1);
max++;
output.addLast("+");
}
arr.removeLast();
output.addLast("-");
if(target > max) max = target;
}
}
br.close();
if(output.contains("no")) {
System.out.println("NO");
}else {
int x = output.size();
for (int i = 0; i < x; i++) {
System.out.println(output.pop());
}
}
}
}
'프로그래밍 > Algorithm' 카테고리의 다른 글
[백준 1110] 플러스 사이클 - 자바 (0) | 2022.06.05 |
---|---|
[백준 2947] 나무 조각 - 자바 (0) | 2022.06.05 |
[백준 11866] 요세푸스 문제 0 - 자바 (0) | 2022.05.23 |
[백준 10828] 스택 - 자바 (0) | 2022.05.23 |
[백준 11637] 인기 투표 - 자바 (0) | 2022.05.23 |