본문 바로가기

코딩테스트/백준

[백준] 10816 : 숫자 카드 2

문제

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

 

10816번: 숫자 카드 2

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

www.acmicpc.net


코드

import sys

n = sys.stdin.readline()
a = sorted(list(map(int, sys.stdin.readline().split())))
m = sys.stdin.readline()
b = list(map(int, sys.stdin.readline().split()))

dic = {}
for i in a:
    if i in dic: # dic의 키에 i번째 요소가 이미 있으면 1추가
        dic[i] += 1
    else: # 없다면 1로 초기화
        dic[i] = 1
for j in b:
    if j in dic: # dic의 키에 j가 있으면 그 값 출력
        print(dic[j], end=' ')
    else: # 없으면 0 출력
        print(0, end=' ')
  • 각 요소의 개수를 확인하는 문제는 딕셔너리가 편하다.
  • 입력 값이 많은 문제는 for문에 list.append()를 사용하지 말자 (시간초과)

다른 사람의 풀이

  • Collections 라이브러리의 Counter 함수
from sys import stdin
from collections import Counter
_ = stdin.readline()
N = stdin.readline().split()
_ = stdin.readline()
M = stdin.readline().split()

C = Counter(N)
print(' '.join(f'{C[m]}' if m in C else '0' for m in M))
  • from collections import Counter
  • Counter(리스트) => 리스트의 각 요소를 딕셔너리로 반환

참고한 블로그

https://chancoding.tistory.com/45