Information Security Study

[백준] 1874: 스택 수열 본문

Programming/JAVA

[백준] 1874: 스택 수열

gayeon_ 2024. 1. 22. 16:51

입출력 예제다.

이미 입력된 숫자가 다시 입력된 경우 NO를 출력한다.

package boj;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException, EmptyStackException{
		// StringBuilder를 사용하여 결과를 한 번에 출력하기 위한 객체 생성
        StringBuilder sb = new StringBuilder();

        // BufferedReader를 사용하여 입력을 받기 위한 객체 생성
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        // 저장할 스택 생성
        Stack<Integer> stack = new Stack<>();
        
        // 입력 횟수
       	int T = Integer.parseInt(br.readLine());
       	
       	int current = 1;
       	
       	// 입력 횟수만큼 반복 
       	for(int i = 0; i < T; i++) {
       		int s = Integer.parseInt(br.readLine());
       		
       		// 현재 숫자부터 입력된 숫자까지 스택에 push
       		while (current <= s) {
       			stack.push(current);
       			sb.append('+').append('\n');
       			current++;
       		}
   			
       		// 스택의 맨 위에 있는 숫자가 입력된 숫자가 같다면 pop
       		if(stack.peek() == s) {
       			stack.pop();
       			sb.append('-').append('\n');
       		} else { // 아니라면 NO 출력 후 return
       			System.out.println("NO");
       			return;
       		}
       		
       	}
       	
       	System.out.println(sb);
	}
	

  

}

 

current는 현재 스택에 넣어야 하는 숫자를 나타낸다.

처음에는 1로 초기화하고 입력된 수열의 숫자와 같아질 때까지 순차적으로 증가한다.

 

입력된 수열이 4 3 6 8 7 5 2 1이라면

처음에는 current가 1이므로 1부터 차례대로 스택에 push되고

그 후에 입력된 수열의 숫자와 비교하면서 필요한 push와 pop 연산을 수행하게 된다.

'Programming > JAVA' 카테고리의 다른 글

[백준] 18258: 큐2  (0) 2024.01.22
[백준] 10845: 큐  (0) 2024.01.22
[백준] 3986: 좋은 단어  (0) 2024.01.19
[백준] 10799: 쇠막대기  (0) 2024.01.19
[백준] 9012: 괄호  (0) 2024.01.19