우선 이 문제를 보자마자 풀이방법이 생각은 났지만 분명 99퍼센트의 확률로 틀렸습니다가 나올만한 풀이였다. 그래도 복습한다는 생각으로 combination을 활용하는 코드를 짜보았다.
import sys
from itertools import combinations
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline())
arr = list(map(str, sys.stdin.readline().split()))
new_arr = combinations(arr, 3)
ans = 0
for i in new_arr:
set1 = set(i[0])
set2 = set(i[1])
set3 = set(i[2])
ans = max(ans, len(set1.intersection(set2)) + len(set2.intersection(set3)) + len(set3.intersection(set1)))
print(12 - ans)
딱 보면 아시겠지만 시간 초과 나게 생긴 코드다. 그래도 뭔가 그냥 넘어가긴 아쉬우니 간단하게 combinations랑 set에 대해서 정리해보았다.
물론입니다, "문체를 보여준다"의 형식에 맞추어서 앞서 언급한 내용을 수정해 보겠습니다.
itertools.combinations
함수combinations(iterable, r)
는 iterable
에서 r
개의 항목을 선택하여 조합을 생성한다.from itertools import combinations
numbers = [1, 2, 3, 4]
for combo in combinations(numbers, 2):
print(combo)
이 코드는 [1, 2, 3, 4]
리스트에서 2개를 선택하는 모든 조합을 보여준다.
from itertools import combinations
string = "ABCD"
for combo in combinations(string, 3):
print(''.join(combo))
이 코드는 "ABCD" 문자열에서 3개의 문자로 이루어진 조합을 보여준다.
set()
함수set()
함수는 반복 가능한 객체로부터 중복을 제거한 요소들의 집합을 생성한다. 예를 들어, 리스트나 문자열에서 중복된 요소를 제거하고 유일한 요소만 남기는 데 사용된다.set()
을 통해 생성된 집합은 교집합, 합집합, 차집합, 대칭 차집합과 같은 기본적인 수학적 집합 연산을 지원한다.my_list = [1, 2, 2, 3, 4, 4, 4, 5]
unique_elements = set(my_list)
print(unique_elements)
이 코드는 리스트 my_list
에서 중복된 요소를 제거하여 유일한 요소만 남기는 집합을 보여준다.
set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
# 교집합
print(set1.intersection(set2))
# 합집합
print(set1.union(set2))
# 차집합
print(set1.difference(set2))
이 코드는 두 집합 사이의 교집합, 합집합, 차집합 연산을 보여준다.
my_set = set([1, 2, 3])
my_set.add(4) # 요소 추가
print(my_set)
my_set.remove(2) # 요소 제거
print(my_set)
이 코드는 집합에 요소를 추가하거나 제거하는 방법을 보여준다.
문항을 보다보니 MBTI의 종류가 16개 밖에 안되니 비둘기집의 원리에 의해 MBTI가 32개 이상인 경우에만 0을 출력해주면 문제가 사라지겠다는 생각이 들었다. 비둘기집의 원리에 대한 설명은 생략하겠습니다. 아래는 코드입니당.
import sys
from itertools import combinations
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline())
arr = list(map(str, sys.stdin.readline().split()))
new_arr = combinations(arr, 3)
ans = 0
if N > 32:
print(0)
continue
for i in new_arr:
set1 = set(i[0])
set2 = set(i[1])
set3 = set(i[2])
ans = max(ans, len(set1.intersection(set2)) + len(set2.intersection(set3)) + len(set3.intersection(set1)))
print(12 - ans)