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

 

알고리즘 분류

  • 자료 구조
  • 스택
  • 난이도 :  실버3
  • 구현 언어 : 자바
  • 소요시간 : 3시간30분
  • 코드
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());
			}
		}
	}
}

 

 

+ Recent posts