|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.StringTokenizer; |
| 5 | + |
| 6 | +public class BJ_17404_RGB거리_2 { |
| 7 | + |
| 8 | + private static final int INF = 987654321; |
| 9 | + |
| 10 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + private static StringTokenizer st; |
| 13 | + |
| 14 | + private static int N, ans; |
| 15 | + private static int[][] colors; |
| 16 | + private static int[][] dp; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + init(); |
| 20 | + sol(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void init() throws IOException { |
| 24 | + N = Integer.parseInt(br.readLine()); |
| 25 | + ans = INF; |
| 26 | + |
| 27 | + colors = new int[N][3]; |
| 28 | + for (int i = 0; i < N; i++) { |
| 29 | + st = new StringTokenizer(br.readLine()); |
| 30 | + for (int j = 0; j < 3; j++) { |
| 31 | + colors[i][j] = Integer.parseInt(st.nextToken()); |
| 32 | + } |
| 33 | + } |
| 34 | + dp = new int[N][3]; |
| 35 | + } |
| 36 | + |
| 37 | + private static void sol() throws IOException { |
| 38 | + // 시작 색 지정 |
| 39 | + for (int firstColor = 0; firstColor < 3; firstColor++) { |
| 40 | + Arrays.fill(dp[0], INF); |
| 41 | + |
| 42 | + dp[0][firstColor] = colors[0][firstColor]; |
| 43 | + |
| 44 | + for (int i = 1; i < N; i++) { |
| 45 | + dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + colors[i][0]; |
| 46 | + dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + colors[i][1]; |
| 47 | + dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + colors[i][2]; |
| 48 | + } |
| 49 | + |
| 50 | + for (int lastColor = 0; lastColor < 3; lastColor++) { |
| 51 | + if (lastColor != firstColor) { |
| 52 | + ans = Math.min(ans, dp[N - 1][lastColor]); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + bw.write(ans + ""); |
| 57 | + bw.flush(); |
| 58 | + bw.close(); |
| 59 | + br.close(); |
| 60 | + } |
| 61 | + |
| 62 | +} |
| 63 | +``` |
0 commit comments