728x90
https://www.acmicpc.net/problem/1158
1158번: 요세푸스 문제
첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000)
www.acmicpc.net
문제)
풀이)
Queue를 생성하여 모든 원소를 넣어두고,
pop한 후 순서에 맞춰 버릴지 queue에 다시 넣을지 결정한다!
이때, 순서에 맞춰 버리는 애는 순서대로 정답 배열에 저장해두고 후에 출력하면 끝!
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main_BJ_1158_요세푸스문제 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int k = sc.nextInt();
Queue<Integer> p = new LinkedList<>();
int[] answer = new int[N];
for(int i=1; i<=N; i++)
p.offer(i);
int count=1;
int index=0;
while(!p.isEmpty()) {
if(count % k == 0) {
answer[index] = p.poll();
index++;
count++;
continue;
}
p.offer(p.poll());
count++;
}
System.out.print("<");
for(int i=0; i<N; i++) {
if(i!=N-1)
System.out.print(answer[i] + ", ");
else
System.out.print(answer[i]);
}
System.out.println(">");
sc.close();
}
}
728x90
'코테 > 백준' 카테고리의 다른 글
백준 2920 음계(JAVA) (1) | 2023.01.09 |
---|---|
백준 17070 파이프 옮기기 1(JAVA) (1) | 2022.09.30 |
백준 2493 탑(JAVA) (0) | 2022.08.17 |
백준 12891. DNA 비밀번호(JAVA) (0) | 2022.08.16 |
백준 2164. 카드2(JAVA) (0) | 2022.08.16 |