[Java] 백준 1158. 요세푸스

정석·2024년 5월 6일
0

알고리즘 학습

목록 보기
27/67
post-thumbnail

🧑🏻‍💻 문제

💡문제 분석 요약

요세푸스에 대한 설명이 문제에서 너무 부실하게 설명되어 있다.
예를 들어 K를 3이라 정했을 때, 계속 반복하며 3번째의 숫자가 빠지게 되는데 빠지고 난 뒤 다음 수부터 다시 첫번째가 된다.

💡알고리즘 설계

  • N 크기의 자료구조 큐를 생성하고 1부터 넣는다.
  • 계속 poll() 을 통해 앞의 값을 맨 뒤로 add() 하고 K 번째 poll() 이 되면 값을 출력한다.

💡코드

public class 백준_10828_스택 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < N; i++) {
            String input = br.readLine();
            String[] tokens = input.split(" ");
            String command = tokens[0];

            // push 명령
            if (command.equals("push")) {
                int temp = Integer.parseInt(tokens[1]);
                stack.push(temp);
            }

            // pop 명령
            if (command.equals("pop")) {
                if (stack.isEmpty()) {
                    System.out.println("-1");
                } else {
                    int value = stack.pop();
                    System.out.println(value);
                }
            }

            // size 명령
            if (command.equals("size")) {
                int size = stack.size();
                System.out.println(size);
            }

            // empty 명령
            if (command.equals("empty")) {
                if (stack.isEmpty()) {
                    System.out.println("1");
                } else {
                    System.out.println("0");
                }
            }

            // top 명령
            if (command.equals("top")) {
                if (stack.isEmpty()) {
                    System.out.println("-1");
                } else {
                    int top = stack.peek();
                    System.out.println(top);
                }
            }
        }
        br.close();
    }
}

0개의 댓글