Post

[BaekJoon] #10816 - 숫자 카드 2 [Java][C++]

[BaekJoon] #10816 - 숫자 카드 2 [Java][C++]

문제 링크


1. 아이디어

$N$이 최대 $500{,}000$이고 각 숫자가 $-10{,}000{,}000$ ~ $10{,}000{,}000$일 때, $M$개의 숫자에 대해 등장 횟수를 출력하는 문제다. 가장 간단하게는 맵을 활용해 등장 횟수를 판단할 수 있고, 주어진 숫자 카드를 정렬한 후 Lower Bound, Upper Bound 이분 탐색을 통해 등장 구간의 길이로 등장 횟수를 구하는 방식으로 해결할 수 있다. 주어진 수의 범위가 크긴 하지만 카운팅 배열을 통해서도 해결할 수 있다.


2. 복잡도

접근시간공간
이분 탐색$O((N + M) \log N)$$O(N)$
카운팅 배열$O(N + M)$$O(K)$
카운팅 맵$O(N + M)$$O(N)$

($N$ = 입력값 n, $M$ = 입력값 m, $K$ = 값의 범위 $2 \times 10^7 + 1$)


3. 코드

풀이 1: 이분 탐색 [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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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;

        int n = Integer.parseInt(br.readLine());

        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr);

        int m = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while (m-- > 0) {
            int x = Integer.parseInt(st.nextToken());
            sb.append(upperBound(arr, x) - lowerBound(arr, x)).append(" ");
        }

        System.out.println(sb);
    }

    static int lowerBound(int[] arr, int key) {
        int lo = 0, hi = arr.length;

        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (arr[mid] < key) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }

        return hi;
    }

    static int upperBound(int[] arr, int key) {
        int lo = 0, hi = arr.length;

        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (arr[mid] <= key) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }

        return hi;
    }
}

Upper Bound의 인덱스에서 Lower Bound의 인덱스를 빼면 해당 원소의 개수를 구할 수 있다.

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

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

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end());

    int m;
    cin >> m;

    while (m--) {
        int x;
        cin >> x;
        cout << upper_bound(v.begin(), v.end(), x) - lower_bound(v.begin(), v.end(), x) << ' ';
    }
}

Upper Bound의 인덱스에서 Lower Bound의 인덱스를 빼면 해당 원소의 개수를 구할 수 있다.

std::upper_bound, std::lower_bound 함수를 활용했다.


풀이 2: 카운팅 배열 [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
import java.io.*;
import java.util.*;

public class Main {

    static final int MAX = 10_000_000;
    static int[] cnt = new int[MAX + 1 + MAX];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        int n = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while (n-- > 0) {
            int x = Integer.parseInt(st.nextToken());
            cnt[x + MAX]++;
        }

        int m = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while (m-- > 0) {
            int x = Integer.parseInt(st.nextToken());
            sb.append(cnt[x + MAX]).append(" ");
        }

        System.out.println(sb);
    }
}

음수 범위도 커버해야 해서 앞에 음수 범위만큼의 패딩을 주어 $-10{,}000{,}000$이 인덱스 0에 매핑되도록 했다.

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
#include <bits/stdc++.h>
using namespace std;

const int MAX = 10'000'000;
int cnt[MAX + 1 + MAX];

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

    int n;
    cin >> n;

    while (n--) {
        int x;
        cin >> x;
        cnt[x + MAX]++;
    }

    int m;
    cin >> m;

    while (m--) {
        int x;
        cin >> x;
        cout << cnt[x + MAX] << ' ';
    }
}

음수 범위도 커버해야 해서 앞에 음수 범위만큼의 패딩을 주어 $-10{,}000{,}000$이 인덱스 0에 매핑되도록 했다.


풀이 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
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;

        Map<Integer, Integer> map = new HashMap<>();

        int n = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while (n-- > 0) {
            int x = Integer.parseInt(st.nextToken());
            map.put(x, map.getOrDefault(x, 0) + 1);
        }

        int m = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        while (m-- > 0) {
            int x = Integer.parseInt(st.nextToken());
            sb.append(map.getOrDefault(x, 0)).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
#include <bits/stdc++.h>
using namespace std;

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

    unordered_map<int, int> mp;

    int n;
    cin >> n;

    while (n--) {
        int x;
        cin >> x;
        mp[x]++;
    }

    int m;
    cin >> m;

    while (m--) {
        int x;
        cin >> x;
        cout << mp[x] << ' ';
    }
}

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