[백준 알고리즘]/[자바 Java]

백준 11866 요세푸스 문제 0 | 자바 java

말하는펭귄 2024. 1. 23. 13:42
728x90
반응형

 

이번 포스팅은 백준 11866번 요세푸스 문제 0입니다.

아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.

https://www.acmicpc.net/problem/11866

 

11866번: 요세푸스 문제 0

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 1,000)

www.acmicpc.net

 

 

 

기본 알고리즘

  • 구현
  • 자료 구조
  • 큐  Queue
//자바 Queue 사용법

//import
import java.util.LinkedList;
import java.util.Queue;

//LinkedList로 선언
Queue<Integer> q = new LinkedList<>();

//삽입
q.add(999);

//삭제
q.remove();
반응형

 

전체 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=0, k=0;
 
        n=sc.nextInt();
        k=sc.nextInt();
 
        Queue<Integer> q = new LinkedList<>();
        int ans[] = new int[n];
 
        for(int i=1; i<=n; i++){
            q.add(i);
        }
 
        int cnt=1, idx=0
        while(!q.isEmpty()){
            int first = q.peek();
            q.remove();
 
            if(cnt%k==0){
                ans[idx++]=first;
            } else {
                q.add(first);
            }
 
            cnt++;
        }
 
        System.out.print("<");
        for(int i=0; i<n-1; i++){
            System.out.print(ans[i]+", ");
        }
        System.out.print(ans[n-1]+">");
 
        sc.close();
    }
}
 
cs

 

 

728x90
반응형