[백준] 1158번 - 요세푸스 문제 [Java][C++]
[백준] 1158번 - 요세푸스 문제 [Java][C++]
1. 문제 풀이
$1$ 번부터 $N$ 번까지의 사람이 원을 이루며 있을 때, $K$ 번째 사람을 제거하는 과정을 반복하는 문제다. 큐 자료구조를 활용하면 간단하게 해결할 수 있는데 큐의 맨 앞을 바라보며 $K$ 번째가 될 때까지 큐에서 꺼내서 큐 뒤에 넣다가 $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
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 << '>';
}
3. 풀이 정보
1. 큐 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 248 ms | 16616 KB | 875 B |
2. 큐 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 48 ms | 2152 KB | 464 B |
This post is licensed under CC BY 4.0 by the author.