백준 10816번 풀이

문제

숫자 카드에서 특정 숫자가 몇 개인지 찾아서 출력하기

Reference

https://www.daleseo.com/python-collections-counter/

https://chancoding.tistory.com/45

풀이

아니 거 카드 몇 장 안되는 거 걍 세면 안되는겨?

아무튼 일단 풀어야 하니 풀어봅시다. 아, 이 문제는 입력 받는 거 배열로 받고 풀 때 딕셔너리가 들어간다. 예시를 보면 아시겠지만 입력에 중복외는 숫자가 있는데 set() 쓰면 이걸 다 쳐버리거든. 입력이 딕셔너리면요? 딕셔너리도 키값 중복되면 다 쳐버린다.

X = int(sys.stdin.readline())
card_list = list(map(int, sys.stdin.readline().split()))
# 카드 입력

Y = int(sys.stdin.readline())
find_list = list(map(int, sys.stdin.readline().split()))
# 찾을거 입력

그러니까 여러분도 얌전히 입력은 리스트로 받으시는 게 정신건강에 이롭습니다.

태그 보니까 이진 탐색이 있다. 그리고 풀이법에서도 이진 탐색 알고리즘을 쓰는데… 그럼 리스트 정렬 안 해요? 뒤에 하심? 아니 그거 안씁니다. collections의 카운터를 갖다 쓸 건데 이거는 걍 counter 만들어놓고 출력만 잘 하면 된다.

import sys
from collections import Counter

X = int(sys.stdin.readline())
card_list = list(map(int, sys.stdin.readline().split()))
# 카드 입력

Y = int(sys.stdin.readline())
find_list = list(map(int, sys.stdin.readline().split()))
# 찾을거 입력

Z = Counter(card_list)

for i in find_list:
    if i in card_list:
        print(Z[i], end=" ")
    else:
        print(0, end=" ")

근데 시간초과… ㅋㅋㅋㅋㅋㅋ 아니 왜때문에?

import sys
from collections import Counter

X = int(sys.stdin.readline())
card_list = list(map(int, sys.stdin.readline().split()))
# 카드 입력

Y = int(sys.stdin.readline())
find_list = list(map(int, sys.stdin.readline().split()))
# 찾을거 입력

Z = Counter(card_list)

print(' '.join(f'{Z[m]}' if m in Z else '0' for m in find_list))

진짜 궁금해서 그러는데 그럼 얘는 어떻게 맞은거임?