알고리즘/백준

[백준 10816] 숫자 카드 2

겜도리도리 2022. 2. 12. 19:04
반응형

문제

https://www.acmicpc.net/problem/10816

 

10816번: 숫자 카드 2

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,

www.acmicpc.net

풀이

map을 이용해서 풀었다.

개수가 50만개라서 시간초과를 걱정하고 풀었는데, 아슬아슬했던 것 같다.

이분 탐색을 쓰면 더 효율적으로 풀 수 있는듯? map 자체도 이분 탐색이긴 하다만

upper_bound와 lower_bound를 쓰면 더 빠르게 풀 수 있다고 함.

소스 코드

map으로 해결

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
#include<iostream>
#include<map>
using namespace std;
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    map<intint> myMap;
    int n, m;
 
    cin >> n;
    int num;
    for (int i = 0; i < n; i++)
    {
        cin >> num;
        myMap[num]++;
    }
 
    cin >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> num;
        cout << myMap[num] << ' ';
    }
 
    return 0;
}
cs

bound로 해결

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
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    vector<int> v;
    int n, m;
 
    cin >> n;
    int num;
    for (int i = 0; i < n; i++)
    {
        cin >> num;
        v.push_back(num);
    }
 
    sort(v.begin(), v.end());
 
    cin >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> num;
        cout << upper_bound(v.begin(), v.end(), num) - lower_bound(v.begin(), v.end(), num) << ' ';
    }
 
    return 0;
}
cs

 

반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 2309] 일곱 난쟁이 C++  (0) 2022.03.30
[백준 1065] 한수 C++  (0) 2022.03.29
[백준 1092] 배 C++  (0) 2021.12.11
[백준 11058] 크리보드 C++  (0) 2021.12.09
[백준 12904] A와 B C++  (0) 2021.12.07