|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.Arrays; |
| 6 | + |
| 7 | +public class Main { |
| 8 | + static int n; |
| 9 | + static int[][][][] dp; |
| 10 | + static int[] start, goal; |
| 11 | + static final int INF = 1000000000; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + n = Integer.parseInt(br.readLine()); |
| 16 | + |
| 17 | + String startStr = br.readLine(); |
| 18 | + String goalStr = br.readLine(); |
| 19 | + |
| 20 | + start = new int[105]; |
| 21 | + goal = new int[105]; |
| 22 | + dp = new int[105][10][10][10]; |
| 23 | + |
| 24 | + // dp 배열 -1로 초기화 |
| 25 | + for (int i = 0; i < 105; i++) { |
| 26 | + for (int j = 0; j < 10; j++) { |
| 27 | + for (int k = 0; k < 10; k++) { |
| 28 | + Arrays.fill(dp[i][j][k], -1); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // 입력 처리 |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + start[i] = startStr.charAt(i) - '0'; |
| 36 | + goal[i] = goalStr.charAt(i) - '0'; |
| 37 | + } |
| 38 | + |
| 39 | + System.out.println(memo(0, start[0], start[1], start[2])); |
| 40 | + } |
| 41 | + |
| 42 | + static int memo(int curr, int a, int b, int c) { |
| 43 | + if (curr == n) { |
| 44 | + return 0; |
| 45 | + } |
| 46 | + |
| 47 | + if (dp[curr][a][b][c] != -1) { |
| 48 | + return dp[curr][a][b][c]; |
| 49 | + } |
| 50 | + |
| 51 | + int ret = INF; |
| 52 | + |
| 53 | + // 시계방향(+1)과 반시계방향(-1) |
| 54 | + for (int i = -1; i <= 1; i += 2) { |
| 55 | + // 현재 위치를 목표값으로 맞추는데 필요한 이동량 |
| 56 | + int mov = rot(rot(goal[curr] - a) * i); |
| 57 | + |
| 58 | + // j: curr+1이 함께 회전하는 양 |
| 59 | + for (int j = 0; j <= mov; j++) { |
| 60 | + // k: curr+2가 함께 회전하는 양 |
| 61 | + for (int k = 0; k <= j; k++) { |
| 62 | + int nb = rot(b + j * i); |
| 63 | + int nc = rot(c + k * i); |
| 64 | + |
| 65 | + // 각각 따로 회전하는 횟수 계산 |
| 66 | + int cost = turn(mov - j) + turn(j - k) + turn(k); |
| 67 | + int tmp = cost + memo(curr + 1, nb, nc, start[curr + 3]); |
| 68 | + |
| 69 | + ret = Math.min(ret, tmp); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return dp[curr][a][b][c] = ret; |
| 75 | + } |
| 76 | + |
| 77 | + // 음수 처리를 위한 회전 함수 |
| 78 | + static int rot(int x) { |
| 79 | + while (x < 0) { |
| 80 | + x += 10; |
| 81 | + } |
| 82 | + return x % 10; |
| 83 | + } |
| 84 | + |
| 85 | + // 회전 횟수 계산 (올림 처리) |
| 86 | + static int turn(int x) { |
| 87 | + return x / 3 + (x % 3 != 0 ? 1 : 0); |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
0 commit comments