|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int n, m; |
| 7 | + static int[] order; |
| 8 | + static int[][][] dp; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + n = Integer.parseInt(br.readLine().trim()); |
| 13 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 14 | + int open1 = Integer.parseInt(st.nextToken()); |
| 15 | + int open2 = Integer.parseInt(st.nextToken()); |
| 16 | + m = Integer.parseInt(br.readLine().trim()); |
| 17 | + order = new int[m]; |
| 18 | + for (int i = 0; i < m; i++) { |
| 19 | + order[i] = Integer.parseInt(br.readLine().trim()); |
| 20 | + } |
| 21 | + |
| 22 | + dp = new int[m + 1][n + 1][n + 1]; |
| 23 | + for (int[][] arr2d : dp) { |
| 24 | + for (int[] arr1d : arr2d) { |
| 25 | + Arrays.fill(arr1d, -1); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + System.out.println(solve(0, open1, open2)); |
| 30 | + } |
| 31 | + |
| 32 | + static int solve(int idx, int a, int b) { |
| 33 | + if (idx == m) return 0; |
| 34 | + if (dp[idx][a][b] != -1) return dp[idx][a][b]; |
| 35 | + |
| 36 | + int target = order[idx]; |
| 37 | + int moveA = Math.abs(target - a) + solve(idx + 1, target, b); |
| 38 | + int moveB = Math.abs(target - b) + solve(idx + 1, a, target); |
| 39 | + |
| 40 | + return dp[idx][a][b] = Math.min(moveA, moveB); |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
0 commit comments