알고리즘/스택, 큐

[알고리즘] 공주 구하기 with Java

VIPeveloper 2022. 3. 22. 18:42
728x90
반응형
import java.util.*;
class Main {

    public static void main(String[] args){
        Main T = new Main();
        Scanner kb = new Scanner(System.in);
        int N = kb.nextInt();
        Queue<Integer> arr = new LinkedList<>();
        for (int i = 1; i <= N; i++) {
            arr.add(i);
        }
        int K = kb.nextInt();
        solution(K,arr);
    }
    private static void solution(int k, Queue<Integer> arr) {
        while(arr.size()!=1){
            Queue<Integer> fq = new LinkedList<>();
            Queue<Integer> bq = new LinkedList<>();
            int size = arr.size();
            if(k>size){
                k -= arr.size();
            }
            for (int i = 1; i <= size; i++) {
                if(i < k){
                    fq.add(arr.poll());
                }else if(i > k){
                    bq.add(arr.poll());
                }else{
                    System.out.println(arr.peek());
                    arr.poll();
                }
            }
            bq.addAll(fq);
            arr = bq;
        }
        System.out.println(arr.poll());
    }
}
728x90
반응형