ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python][C++] 10816번 숫자 카드 2
    Algorithm/Baekjoon 2024. 6. 28. 21:12

    문제

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

     

     

     

     

    코드

    1. Python

    from collections import defaultdict
    
    n = int(input())
    cards = list(map(int, input().split()))
    m = int(input())
    query = [*map(int, input().split())]
    
    card_count = defaultdict(int)
    
    for card in cards:
        card_count[card] += 1
    
    for q in query:
        print(card_count[q], end=' ')

     

    2. C++

    #include <iostream>
    #include <unordered_map>
    using namespace std;
    
    int main() {
    	ios::sync_with_stdio(false);
    	cin.tie(nullptr);
    	cout.tie(nullptr);
    
    	int n, m;
    	
    	cin >> n;
    
    	unordered_map<int, int> card_count;
    	int card;
    
    	while (n--) {
    		cin >> card;
    		card_count[card] += 1;
    	}
    
    	cin >> m;
    
    	while (m--) {
    		cin >> card;
    		cout << card_count[card] << " ";
    	}
    
    	return 0;
    }

     

     

    풀이

    이 문제는 해당 숫자 카드가 몇 번 나왔는지 카운트하는 문제다. 배열을 사용하기에는 숫자의 범위가 넓으므로 메모리 낭비를 줄이기 위해 맵을 활용하는게 좋다.

     

    맵을 사용할 때, 주의할 점이 있다.

     

    C++에서는 map보다는 unoredered_map을 활용하는게 좋다. 이유는 unordered_map은 해시 테이블 기반으로 만들어져서 대부분의 작업이 O(1)의 시간으로 해결이 가능하다. map은 O(log n)

     

    파이썬에서는 dict 보다 defaultdict을 사용하는게 좋다. 이유는 dict는 C++ map이나 파이썬 defaultdict과는 다르게 자동으로 초기값을 설정해주지 않기 때문에, += 1 같은 연산을 수행할 때, 키가 사전에 존재하지 않으면 오류가 발생한다.

    'Algorithm > Baekjoon' 카테고리의 다른 글

    [Python][C++] 10845번 큐  (0) 2024.06.29
    [Python][C++] 10828번 스택  (0) 2024.06.29
    [Python][C++] 10814번 나이순 정렬  (0) 2024.06.27
    [Python][C++] 10773번 제로  (0) 2024.06.27
    [파이썬/Python] 9012번 괄호  (0) 2024.06.13
Designed by Tistory.