[BaekJoon] #2161 - 카드1 [Java][C++]
[BaekJoon] #2161 - 카드1 [Java][C++]
1. 아이디어
$N$장의 카드를 1부터 $N$까지 뭉치를 만든 후, 제일 위 카드를 버리고 다음 카드를 가장 밑에 두는 과정을 반복했을 때, 버려지는 카드들을 순서대로, 마지막에 남은 카드까지 출력하는 문제로 큐 자료구조를 활용해서 버리는 카드는 큐의 맨 앞 원소를 꺼내서 출력하는 것으로, 다음 카드를 가장 밑에 두는 것은 큐의 맨 앞 원소를 큐의 맨 뒤에 삽입하는 것으로 치환해서 해결할 수 있다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 n)
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
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();
int n = Integer.parseInt(br.readLine());
Queue<Integer> q = new ArrayDeque<>();
for (int i = 1; i <= n; i++) {
q.offer(i);
}
while (q.size() > 1) {
sb.append(q.poll()).append(" ");
q.offer(q.poll());
}
sb.append(q.poll());
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
queue<int> q;
for (int i = 1; i <= n; i++) {
q.push(i);
}
while (q.size() > 1) {
cout << q.front() << ' ';
q.pop();
q.push(q.front());
q.pop();
}
cout << q.front();
}
This post is licensed under CC BY 4.0 by the author.