PS/Java

[백준] 1158번: 요세푸스 문제

siyamaki 2021. 3. 9. 16:03

요세푸스 문제는 다음과 같다.

1번부터 N번까지 N명의 사람이 원을 이루면서 앉아있고, 양의 정수 K(≤ N)가 주어진다.

 

이제 순서대로 K번째 사람을 제거한다. 한 사람이 제거되면 남은 사람들로 이루어진 원을 따라 이 과정을 계속해 나간다.

 

이 과정은 N명의 사람이 모두 제거될 때까지 계속된다. 원에서 사람들이 제거되는 순서를 (N, K)-요세푸스 순열이라고 한다.

 

예를 들어 (7, 3)-요세푸스 순열은 <3, 6, 2, 7, 5, 1, 4>이다.


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 요세푸스 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();

        int k = scanner.nextInt();

        Queue<Integer> queue = new LinkedList<>();

        for(int i = 1; i <= n; i++) {
            queue.offer(i);
        }

        StringBuilder sb = new StringBuilder();
        sb.append("<");

        int count = 1;
        while(!queue.isEmpty()) {
            int t = queue.poll();
            if(count == k) {
                sb.append(t + ", ");
                count = 1;
            } else {
                queue.offer(t);
                count++;
            }
        }

        String result = sb.substring(0, sb.length() - 2);
        System.out.println(result + ">");
    }
}

Queue를 사용하였다. 

 

count를 이용하여 한바퀴 넘어갈 때 어떻게 변해야 하는지 조절하였다.