[BaekJoon] 1158번 - 요세푸스 문제 [Java][C++]
[BaekJoon] 1158번 - 요세푸스 문제 [Java][C++]
1. 문제 풀이
BaekJoon 11866번 - 요세푸스 문제 0 에서 $N$ 과 $K$ 의 범위가 더 커진 문제로 여전히 큐를 활용하면 동일하게 해결할 수 있다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
Queue<Integer> q = new ArrayDeque<>();
for (int i = 1; i <= N; i++) {
q.offer(i);
}
sb.append("<");
while (!q.isEmpty()) {
for (int i = 1; i < K; i++) {
q.offer(q.poll());
}
sb.append(q.poll());
if (!q.isEmpty()) {
sb.append(", ");
}
}
sb.append(">");
System.out.println(sb);
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
queue<int> q;
for (int i = 1; i <= n; i++) q.push(i);
cout << '<';
while (!q.empty()) {
for (int i = 1; i < k; i++) {
q.push(q.front());
q.pop();
}
cout << q.front();
q.pop();
if (!q.empty()) cout << ", ";
}
cout << '>';
}
This post is licensed under CC BY 4.0 by the author.