ALGORITHM

[JAVA] 알고리즘 : Queue- 공주 구하기

연듀 2022. 7. 14. 15:41

 

import java.util.*;

public class Main {
    public int solution(int n, int k){
        int answer=0;
        Queue<Integer> Q = new LinkedList<>();
        for(int i=1; i<=n; i++) Q.offer(i); // 큐 세팅
        while(!Q.isEmpty()){ // 큐가 비어있지 않을 때
            for(int i=1; i<k; i++){
                Q.offer(Q.poll()); // k-1번만큼 큐에서 꺼낸 값을 맨 뒤에 추가
            }
            Q.poll(); // k번째 숫자는 큐에서 제거
            if(Q.size() == 1) answer=Q.poll(); // 마지막으로 남은 숫자
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int k=sc.nextInt();
        System.out.println(T.solution(n,k));
    }
}