BOJ 1874 스택 수열

1 개요[ | ]

BOJ 1874 스택 수열
  • 스택이 가지는 성질에 대해 고민하고 관련 문제를 해결해 봅니다
  • 알고리즘 분류: 스택

2 Java[ | ]

Java
Copy
import java.util.Stack;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class Main {
	public static void main(String args[]) throws IOException {
		BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
		BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( System.out ) );
		int i, n = Integer.parseInt(br.readLine());
		int[] inputs = new int[n];
		for(i=0; i<n; i++) inputs[i] = Integer.parseInt(br.readLine());
		Stack<Integer> stack = new Stack<Integer>();
		int pos = 0;
		ArrayList<String> actions = new ArrayList<String>();
		for(i=0; i<n; i++) {
			stack.push(i+1);
			actions.add("+");
			while( !stack.isEmpty() && stack.peek() == inputs[pos] ) {
				stack.pop();
				actions.add("-");
				pos++;
			}
		}
		if( !stack.isEmpty() ) {
			System.out.println("NO");
			return;
		}
		for(String action: actions) bw.write( action+"\n" );
		bw.flush();
	}
}