본문 바로가기

알고리즘/스택

1894번 스택수열

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;


public class Main {
	static Stack<Integer> stack;
	static int arr[];
	static int index=1;
	public static void main(String[] args) {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
		StringBuffer sf=new StringBuffer();
		try {
			String tempCase=br.readLine();
			 stack=new Stack<Integer>();
			int testCaseCnt=Integer.parseInt(tempCase);
			String tempCnt="0";
			int cnt=0;
			boolean isCheck=false;
			arr=new int[testCaseCnt];
			for(int i=0;i<testCaseCnt;i++){
				tempCnt=br.readLine();
				cnt=Integer.parseInt(tempCnt);
				arr[i]=cnt;
				if(!isCheck){
					if(index<=cnt){
						for(int j=index;j<=cnt;j++){
							stack.push(index);
							index++;
							sf.append("+"+"\n");
							if(j==cnt){
								if(stack.isEmpty()){
									break;
								}
								stack.pop();
								sf.append("-"+"\n");
							}
						}
					}else{
						if(stack.isEmpty()||stack.peek()>cnt){
							if(testCaseCnt>i){
								isCheck=true;
							}
							break;
						}
						for(int j=stack.peek();j>=cnt;j--){
							stack.pop();
							sf.append("-"+"\n");
						}
					}
				}
			}
			if(isCheck){
				bw.write("NO");
			}else{
				bw.write(sf.toString());
			}
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(bw!=null){
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

java.io.BufferedReader;

'알고리즘 > 스택' 카테고리의 다른 글

1406번 에디터  (0) 2020.06.21
9012번 괄호  (0) 2020.06.11
9093번 단어 뒤집기  (0) 2020.06.07
10828번 스택  (0) 2020.06.07