Post

[BaekJoon] 2161번 - 카드1 [Java][C++]

[BaekJoon] 2161번 - 카드1 [Java][C++]

문제 링크


1. 문제 풀이


$N$ 장의 카드를 $1$ 부터 $N$ 까지 뭉치를 만든 후, 제일 윗 카드를 버리고 다음 카드를 가장 밑에 두는 과정을 반복했을 때, 버려지는 카드들을 순서대로 출력하는 문제로 큐 자료구조를 활용해서 버리는 카드는 큐의 맨 앞 원소를 꺼내서 출력하는 것으로, 다음 카드를 가장 밑에 두는 것은 큐의 맨 앞 원소를 큐의 맨 뒤에 삽입하는 것으로 치환해서 해결할 수 있다.


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
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);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    deque<int> q(n);
    iota(q.begin(), q.end(), 1);

    while (q.size() > 1) {
        cout << q.front() << ' ';
        q.pop_front();

        q.push_back(q.front());
        q.pop_front();
    }
    cout << q.front();
}

This post is licensed under CC BY 4.0 by the author.