RGB거리에는 집이 N개 있다. 거리는 선분으로 나타낼 수 있고, 1번 집부터 N번 집이 순서대로 있다.
집은 빨강, 초록, 파랑 중 하나의 색으로 칠해야 한다. 각각의 집을 빨강, 초록, 파랑으로 칠하는 비용이 주어졌을 때, 아래 규칙을 만족하면서 모든 집을 칠하는 비용의 최솟값을 구해보자.
첫째 줄에 집의 수 N(2 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 각 집을 빨강, 초록, 파랑으로 칠하는 비용이 1번 집부터 한 줄에 하나씩 주어진다. 집을 칠하는 비용은 1,000보다 작거나 같은 자연수이다.
첫째 줄에 모든 집을 칠하는 비용의 최솟값을 출력한다.
dp 배열은 n x 3 크기로, dp[i][j] 는 i 번째 집의 색이 j일 때 소모되는 누적비용이다.getCost(n, color) 함수는 n번째 집이 color 색일 때의 dp[n][color] 값을 반환하는 함수이다.dp[k][color])cost 배열에 모두 받아놓는다.k - 1 번째 집에 대해, k 번째 집과 다른 나머지 두 색깔의 dp[k-1][color] 을 비교해 최솟값을 구한다.dp 값을 구하기 위해 getCost(k-1, color) 함수를 재귀호출 할 것이다.k 번째집의 color 비용을 더하면 dp[k][color] 값이 된다.import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Baekjoon_1149 {
final static int RED = 0;
final static int GREEN = 1;
final static int BLUE = 2;
static int[][] cost;
static int[][] dp;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
cost = new int[n][3];
dp = new int[n][3];
StringTokenizer st;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
cost[i][RED] = Integer.parseInt(st.nextToken());
cost[i][GREEN] = Integer.parseInt(st.nextToken());
cost[i][BLUE] = Integer.parseInt(st.nextToken());
}
dp[0][RED] = cost[0][RED];
dp[0][GREEN] = cost[0][GREEN];
dp[0][BLUE] = cost[0][BLUE];
System.out.println(Math.min(getCost(n-1, RED), Math.min(getCost(n-1, GREEN), getCost(n-1, BLUE))));
}
static int getCost(int n, int color){
if(dp[n][color] == 0){
if(color == RED){
dp[n][RED] = Math.min(getCost(n-1, GREEN), getCost(n-1, BLUE)) + cost[n][RED];
} else if(color == GREEN){
dp[n][GREEN] = Math.min(getCost(n-1, RED), getCost(n-1, BLUE)) + cost[n][GREEN];
}else{
dp[n][BLUE] = Math.min(getCost(n-1, GREEN), getCost(n-1, RED)) + cost[n][BLUE];
}
}
return dp[n][color];
}
}