Home BOJ. RGB Distance 2 (17404)
Post
Cancel

BOJ. RGB Distance 2 (17404)

[Link] https://www.acmicpc.net/problem/17404


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		int n = toi(br.readLine());
		int[] arr;
		int[][] dp0 = new int[n + 1][3];
		int[][] dp1 = new int[n + 1][3];
		int[][] dp2 = new int[n + 1][3];
		for(int[] ar: dp0) Arrays.fill(ar, 55555555);
		for(int[] ar: dp1) Arrays.fill(ar, 55555555);
		for(int[] ar: dp2) Arrays.fill(ar, 55555555);
		arr = getArr();
		dp0[1][0] = arr[0];
		dp1[1][1] = arr[1];
		dp2[1][2] = arr[2];

		for(int i = 2; i < n; i++) {
			arr = getArr();
			dp0[i][0] = Math.min(dp0[i-1][1], dp0[i-1][2]) + arr[0];
			dp0[i][1] = Math.min(dp0[i-1][0], dp0[i-1][2]) + arr[1];
			dp0[i][2] = Math.min(dp0[i-1][0], dp0[i-1][1]) + arr[2];

			dp1[i][0] = Math.min(dp1[i-1][1], dp1[i-1][2]) + arr[0];
			dp1[i][1] = Math.min(dp1[i-1][0], dp1[i-1][2]) + arr[1];
			dp1[i][2] = Math.min(dp1[i-1][0], dp1[i-1][1]) + arr[2];

			dp2[i][0] = Math.min(dp2[i-1][1], dp2[i-1][2]) + arr[0];
			dp2[i][1] = Math.min(dp2[i-1][0], dp2[i-1][2]) + arr[1];
			dp2[i][2] = Math.min(dp2[i-1][0], dp2[i-1][1]) + arr[2];
		}

		arr = getArr();
		ArrayList<Integer> al = new ArrayList<>();
		al.add(dp0[n - 1][0] + arr[1]);
		al.add(dp0[n - 1][2] + arr[1]);
		al.add(dp0[n - 1][0] + arr[2]);
		al.add(dp0[n - 1][1] + arr[2]);

		al.add(dp1[n - 1][1] + arr[0]);
		al.add(dp1[n - 1][2] + arr[0]);
		al.add(dp1[n - 1][0] + arr[2]);
		al.add(dp1[n - 1][1] + arr[2]);

		al.add(dp2[n - 1][1] + arr[0]);
		al.add(dp2[n - 1][2] + arr[0]);
		al.add(dp2[n - 1][0] + arr[1]);
		al.add(dp2[n - 1][2] + arr[1]);

		println(Collections.min(al));
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static long tol(String s) { return Long.parseLong(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.