[BaekJoon] #11866 - 요세푸스 문제 0 [Java][C++]
[BaekJoon] #11866 - 요세푸스 문제 0 [Java][C++]
1. 아이디어
1번부터 $N$번까지 $N$명의 사람이 원을 이루며 있을 때, $K$번째 사람을 제거하는 과정을 반복하는 문제다. 큐 자료구조를 활용하면 간단하게 해결할 수 있는데 1부터 $N$까지를 순서대로 큐에 넣은 뒤 큐의 맨 앞을 바라보며 $K$번째가 될 때까지 큐에서 꺼내서 큐 뒤에 넣다가 $K$번째면 큐에서 꺼내고 출력하는 과정을 큐가 빌 때까지 반복하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \times K)$ | $O(N)$ |
($N$ = 입력값 n, $K$ = 입력값 k)
3. 코드
풀이 [Java][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
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);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
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.