https://www.acmicpc.net/problem/11866
11866번: 요세푸스 문제 0
첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 1,000)
www.acmicpc.net
처음에는 ArrayList를 사용할까 고민했다. 근데 생각해보니 현재 체크한 숫자가 조건에 맞지 않는 경우, 제일 나중에 검사하겠다는 것 자체가 결국 큐의 맨 뒤로 보내는 것이므로 이 성질을 이용하여 해결했다.
문제 및 입출력
코드
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
Queue<Integer> q = new LinkedList<Integer>();
int n = sc.nextInt();
int k = sc.nextInt();
int cnt = 1;
// 1~n까지 큐에 초기 설정
for(int i=1; i<=n; i++)
{
q.add(i);
}
sb.append("<");
while(q.size()!=1)
{
// k번째 숫자는 큐에서 빼고 cnt 변수를 초기화
if(cnt==k)
{
sb.append(q.poll() + ", ");
cnt = 1;
}
// 숫자 k개를 체크할 때까지 현재 값을 큐의 맨 뒤로 보내기
else
{
q.add(q.poll());
cnt++;
}
}
sb.append(q.poll() + ">");
System.out.println(sb.toString());
sc.close();
}
}
'[ 다먹살 ] > - Coding' 카테고리의 다른 글
[백준] 11399 ATM (0) | 2021.11.09 |
---|---|
[백준] 17219 비밀번호 찾기 (0) | 2021.11.08 |
[백준] 11050 이항계수1 (0) | 2021.11.07 |
[백준] 10816 숫자 카드2 (0) | 2021.11.05 |
[백준] 2920 음계 (0) | 2021.11.04 |
댓글