문제 파악
https://www.acmicpc.net/problem/1041
어려운 점
주사위의 합을 구하는 규칙이 분명 존재할 것 같은데 생각보다 경우의 수가 적을 것 같아 직접 배열에 선언하는 단순한 방식을 사용했다.
이 배열을 만들어주는 게 오히려 어려웠다... 😅
풀이
한 면, 두 면, 세 면이 보이는 3개의 경우로 나뉜다.
하나의 주사위 배치가 다른 주사위에 영향을 미치지 않기 때문에 독립적이라고 볼 수 있겠다.
세 경우에서 가장 적은 합을 구해 각 면이 발생하는 개수를 곱해 주면 원하는 값을 구할 수 있다.
먼저 각 경우의 발생 개수를 구해보자면
한 면 : (N-2) ^ 2 + (N-1)(N-2)*4
두 면 : (N-2) * 8 + 4
세 면 : 4
이 되겠다. 바닥 부분 때문에 개수에 영향이 감에 유의하도록 하자.
이를 주사위의 최소값을 구해 놓은 것에 각각 곱하자.
2차원 배열을 선언하여 주사위의 인덱스에 해당하는 값을 저장하였다.
3면에 해당하는 경우는 꼭지점에 해당하기에 8개이다
{0, 1, 2}, {0, 1, 3}, {0, 2, 4}, {0, 3, 4}, {1, 2, 5}, {1, 3, 5}, {2, 4, 5}, {3, 4, 5}
2면에 해당하는 경우는 모서리에 해당하며 12(4*3)개 가량이다
{0, 1}, {0, 2}, {0, 3}, {0, 4},
{1, 2}, {1, 3}, {1, 5},
{2, 4}, {2, 5},
{3, 4}, {3, 5},
{4, 5}
위 배열을 순환하며 최소값을 구한 다음, 연산해주도록 하자
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] dice = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::valueOf).toArray();
if (n == 1) {
System.out.println(oneCase(dice));
return;
}
long one = (long) Math.max(0, n - 2) * Math.max(0, n - 2) + (long) Math.max(0, n - 2) * Math.max(0, n - 1) * 4;
long two = Math.max(0, n - 2) * 8L + 4L;
long three = 4;
long oneValue = minOne(dice);
long twoValue = minTwo(dice);
long threeValue = minThree(dice);
System.out.println(one * oneValue + two * twoValue + three * threeValue);
}
static long minThree(int[] dice) {
final int[][] info = new int[][]{
{0, 1, 2}, {0, 1, 3}, {0, 2, 4}, {0, 3, 4},
{1, 2, 5}, {1, 3, 5}, {2, 4, 5}, {3, 4, 5}
};
return sumOfArr(dice, info);
}
static long minTwo(int[] dice) {
final int[][] info = new int[][]{
{0, 1}, {0, 2}, {0, 3}, {0, 4},
{1, 2}, {1, 3}, {1, 5},
{2, 4}, {2, 5},
{3, 4}, {3, 5},
{4, 5}
};
return sumOfArr(dice, info);
}
static long minOne(int[] dice) {
return Arrays.stream(dice).min().orElse(0);
}
static int oneCase(int[] dice) {
int max = 0;
int sum = 0;
for (int d : dice) {
sum += d;
max = Math.max(max, d);
}
return sum - max;
}
static int sumOfArr(int[] dice, int[][] arr) {
int min = Integer.MAX_VALUE;
for (int[] a : arr) {
int sum = Arrays.stream(a).map(d -> dice[d]).sum();
min = Math.min(sum, min);
}
return min;
}
}
'Algorithm' 카테고리의 다른 글
[백준] 1099 - 알 수 없는 문장(Java) (0) | 2025.01.11 |
---|---|
[백준] 1052 - 물병(Java) (0) | 2024.12.31 |
[프로그래머스] 12904 - 가장 긴 팰린드롬 (Java) (0) | 2024.10.07 |
[프로그래머스] 161988 - 연속 펄스 부분 (0) | 2024.10.06 |
[프로그래머스] 340212 - 퍼즐 게임 챌린지 (2) | 2024.09.09 |