알고리즘 공부/기타
[백준] 9375번 패션왕 신해빈- 파이썬
코딩 코딩 코오딩
2022. 3. 2. 17:31
https://www.acmicpc.net/problem/9375
9375번: 패션왕 신해빈
첫 번째 테스트 케이스는 headgear에 해당하는 의상이 hat, turban이며 eyewear에 해당하는 의상이 sunglasses이므로 (hat), (turban), (sunglasses), (hat,sunglasses), (turban,sunglasses)로 총 5가지 이다.
www.acmicpc.net
이 문제는 그렇게 어렵지 않았다.
경우의 수를 생각하고 하면 된다.
dict는 꼭 필요한 함수이니 꼭 숙지하고 암기해두자
그리고 여러개의 value를 활용할 수 있으니
if kind not in keys:
keys.append(kind)
if kind in cloth:
cloth[kind].append(name)
else:
cloth[kind] = [name]
이부분 꼭 알아두자
import sys
from itertools import combinations
T = int(sys.stdin.readline().rstrip())
for i in range(T):
n = int(sys.stdin.readline().rstrip())
cloth = {}
answer = 1
keys = []
for j in range(n):
name , kind = sys.stdin.readline().rstrip().split()
if kind not in keys:
keys.append(kind)
if kind in cloth:
cloth[kind].append(name)
else:
cloth[kind] = [name]
for key in cloth:
a = (len(cloth[key])+1)
answer *= a
answer -= 1
print(answer)
처음에 풀어보려했던 방법인데 메모리가 초과된다.
답은 맞게 나온다
모든 경우를 고려하려다 보니 어쩔 수 없나보다.
import sys
from itertools import combinations
T = int(sys.stdin.readline().rstrip())
for i in range(T):
n = int(sys.stdin.readline().rstrip())
cloth = {}
answer = 1
keys = []
for j in range(n):
name , kind = sys.stdin.readline().rstrip().split()
if kind not in keys:
keys.append(kind)
if kind in cloth:
cloth[kind].append(name)
else:
cloth[kind] = [name]
combi = []
for j in range(1, len(keys)+1):
combi.append(list(combinations(keys,j)))
for j in range(len(combi)):
for k in range(len(combi[j])):
a = 1
for l in range(len(combi[j][k])):
if len(combi[j][k]) ==1:
answer += len(cloth[combi[j][k][l]])
else:
a *= len(cloth[combi[j][k][l]])
if a == 1:
answer += 0
else:
answer += a
print(answer)
참고할거
https://devpouch.tistory.com/66
[Python] 딕셔너리에 키가 있는지 체크하기
딕셔너리에 존재하지 않는 키에 접근하는 경우 파이썬은 KeyError를 발생시킵니다. 그러므로 딕셔너리에 접근할 때에는 키값을 체크해주고 접근하는 것이 안전한데요. 파이썬에서 키를 체크하는
devpouch.tistory.com
https://www.delftstack.com/ko/howto/python/number-of-keys-in-dictionary-python/
사전 Python의 키 개수 계산
이 자습서에서는 Python 사전에서 키 수를 계산하는 방법을 보여줍니다.
www.delftstack.com
반응형