문제풀이/구현

[Python/파이썬] 백준 1041번 주사위

딜레이레이 2025. 3. 23. 23:51

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

코드

from itertools import combinations

n = int(input())
dice = list(map(int, input().split()))

one_min = min(dice)

two_min = int(1e9)
for comb in combinations(range(6), 2):
    if sum(comb) == 5:
        continue
    total = dice[comb[0]]+dice[comb[1]]
    if total < two_min:
        two_min = total

three_min = int(1e9)
for comb in combinations(range(6), 3):
    if comb[0]+comb[1] == 5 or comb[1]+comb[2] == 5 or comb[0]+comb[2] == 5:
        continue
    total = dice[comb[0]]+dice[comb[1]]+dice[comb[2]]
    if total < three_min:
        three_min = total

answer = 0
if n == 1:
    answer = sum(dice)-max(dice)
elif n == 2:
    answer += two_min*4
    answer += three_min*4
else:
    answer += one_min*((n-2)**2 + (n-1)*(n-2)*4)
    answer += two_min*((n-2)*4+(n-1)*4)
    answer += three_min*4

print(answer)

 

5개의 면에서 어느 부분이 1면만 노출될지, 2면이 노출될지, 3면이 노출될지 생각해보면 다음과 같다.

 

빨간색으로 표시된 모서리는 3면, 민트색 표시는 2면, 그 외에는 1면이 노출되게 된다.

그래서 각 케이스(1면, 2면, 3면)에서 최솟값을 구해서 다음과 같이 구하면 된다.

answer += one_min*((n-2)**2 + (n-1)*(n-2)*4)
answer += two_min*((n-2)*4+(n-1)*4)
answer += three_min*4

 

근데 최솟값을 구할 때 주의해야 할 점은 2면이나 3면을 고를 때 서로 마주보고 있는 면을 같이 고르면 안된다는 점이다. 이런 케이스를 거르기 위해서 주사위(1 2 3 4 5 6)에서 마주보는 면은 합이 7이라는 점을 이용했다.


잘했다고 생각하고 제출했는데 90퍼에서 틀렸다ㅠ

다시 생각해보니 n이 1일 때와 2일 때는 위와 같이 3가지 경우로 나눠서 풀 수 없다. 그렇기 때문에 이런 케이스들을 예외 처리해주었더니 통과됐다.

 

예외처리를 잘하자!