Post

[BaekJoon] 2164번 - 카드2 [Java][C++]

[BaekJoon] 2164번 - 카드2 [Java][C++]

문제 링크


1. 문제 풀이


BaekJoon 2161번 - 카드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
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));

        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) {
            q.poll();
            q.offer(q.poll());
        }

        System.out.println(q.peek());
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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) {
        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.