[백준][1158번] 요세푸스

Updated:

나의 풀이

package backjoon;

import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        StringBuilder answer = new StringBuilder();
        int N = sc.nextInt();
        int K = sc.nextInt();

        Queue<Integer> q = new LinkedList<>();
        for(int i=1; i<=N; i++)
            q.add(i);

        answer.append("<");
        int cnt=0;
        while(!q.isEmpty()){
            cnt++;
            if(cnt == K){
                int n = q.poll();
                if(q.isEmpty()) {
                    answer.append(n);
                    break;
                }
                answer.append(n+", ");
                cnt=0;
            }else{
                q.add(q.poll());
            }
        }
        answer.append(">");

        System.out.println(answer);
    }
}

다른 풀이

import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        sb.append('<');
        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i=1; i<=n; i++) {
            queue.offer(i);
        }
        for (int i=0; i<n-1; i++) {
            for (int j=0; j<m-1; j++) {
                queue.offer(queue.poll());
            }
            sb.append(queue.poll() + ", ");
        }
        sb.append(queue.poll() + ">");
        System.out.println(sb);
    }
}

느낀점 키워드

  1. queue의 FIFO(선입선출)의 원리를 이용한

Leave a comment