[ 기타 ]/코딩테스트
[백준/JAVA] 11866번 : 요세푸스문제 0 / Queue 자료구조
HSRyuuu
2023. 6. 5. 13:31
문제 풀러 가기 : https://www.acmicpc.net/problem/11866
이 문제는 Queue 자료구조를 이용하면 매우 간단하다.
K회 반복하는 for문을 돌며 queue에서 값을 꺼내고, 다시 넣기를 반복하다가,
K번째 반복에서는 다시 넣지 않고 출력하기를 반복하면 된다.
이 반복을 queue.size() == 1이 될때 까지 반복하고, 마지막 남은 원소를 출력하고 마무리 한다.
Code
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
StringBuilder sb = new StringBuilder();
sb.append("<");
Queue<Integer> queue = new LinkedList<>();
for(int i=1;i<=n;i++){
queue.offer(i);
}
int cnt = 0;
while(queue.size()!=1){
int data = queue.poll();
cnt++;
if(cnt%k == 0){
sb.append(data).append(", ");
}else queue.add(data);
}
sb.append(queue.poll()).append(">");
System.out.println(sb);
}
}
반응형