뚱땅뚱땅

[문제] 백준 1158번 요세푸스 문제 본문

알고리즘/백준

[문제] 백준 1158번 요세푸스 문제

양순이 2021. 2. 9. 13:34
728x90

* www.acmicpc.net/problem/1158

 

1158번: 요세푸스 문제

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

www.acmicpc.net

 

내 풀이

 

큐에다 넣다뺐다 하면 된다. 큐로 풀 수 있다고 생각하면 쉬운 문제다.

 

public class BOJ_1158 {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();

		String s[] = in.readLine().split(" ");
		sb.append("<");
		int N = Integer.parseInt(s[0]);
		int K = Integer.parseInt(s[1]);

		Queue<Integer> queue = new LinkedList<Integer>();

		for (int i = 1; i <= N; i++) {
			queue.offer(i);
		}
	// 큐가 빌 때까지 반복
		while (!queue.isEmpty()) {	
			for(int i=1;i<K;i++)
				queue.offer(queue.poll());	//K-1개만큼 큐에서 빼기

			sb.append(queue.poll()).append(", ");	// K번째 큐 출력
		}

		sb.setLength(sb.length() - 2);
		sb.append(">");
		System.out.println(sb);

	}

}
728x90
Comments