RGB거리(1149)
i번째 집을 각각의 색으로 칠할 때, i-1번째 집을 모두 칠하는 최소 비용으로 부분문제
문제
RGB거리에는 집이 N개 있다. 거리는 선분으로 나타낼 수 있고, 1번 집부터 N번 집이 순서대로 있다.
집은 빨강, 초록, 파랑 중 하나의 색으로 칠해야 한다. 각각의 집을 빨강, 초록, 파랑으로 칠하는 비용이 주어졌을 때, 아래 규칙을 만족하면서 모든 집을 칠하는 비용의 최솟값을 구해보자.
1번 집의 색은 2번 집의 색과 같지 않아야 한다.
N번 집의 색은 N-1번 집의 색과 같지 않아야 한다.
i(2 ≤ i ≤ N-1)번 집의 색은 i-1번, i+1번 집의 색과 같지 않아야 한다.
시간 제한
0.5초
입력
첫째 줄에 집의 수 N(2 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 각 집을 빨강, 초록, 파랑으로 칠하는 비용이 1번 집부터 한 줄에 하나씩 주어진다. 집을 칠하는 비용은 1,000보다 작거나 같은 자연수이다.
출력
첫째 줄에 집의 수 N(2 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 각 집을 빨강, 초록, 파랑으로 칠하는 비용이 1번 집부터 한 줄에 하나씩 주어진다. 집을 칠하는 비용은 1,000보다 작거나 같은 자연수이다.
예제 입력
3
26 40 83
49 60 57
13 89 99
예제 출력
모든 경우의 수를 내려가면서 구해야하기 때문에 R,G,B모두 다 검색하면서 찾아봐야한다
풀이
import java.io.*;
import java.util.*;
public class Main{
static int arr[][];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
arr = new int[N][3];
for(int i=0; i<N; i++){
st = new StringTokenizer(br.readLine(), " ");
for (int j = 0; j < 3; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i=1; i<N; i++){
arr[i][0] = Math.min(arr[i-1][1], arr[i-1][2])+arr[i][0];
arr[i][1] = Math.min(arr[i-1][0], arr[i-1][2])+arr[i][1];
arr[i][2] = Math.min(arr[i-1][0], arr[i-1][1])+arr[i][2];
}
System.out.println(Math.min(arr[N-1][0], Math.min(arr[N-1][1], arr[N-1][2])));
}
}
백준
2번째 시도
이게보니까 굳이 새로운 배열을 만들어서 값을 넣을필요도없이 그냥 입력받은 배열에다가 새로운값으로 최신화시키면서 진행하는 방법도 있더라..!
배열을 하나 더 사용해서 그런가 조금은 메모리와 시간이 더 들었다
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(bf.readLine());
int[][] dp = new int[n][3];
int[][] cnt = new int[n][3];
for(int i=0; i<n; i++){
st = new StringTokenizer(bf.readLine(), " ");
dp[i][0] = Integer.parseInt(st.nextToken());
dp[i][1] = Integer.parseInt(st.nextToken());
dp[i][2] = Integer.parseInt(st.nextToken());
}
cnt[0][0] = dp[0][0];
cnt[0][1] = dp[0][1];
cnt[0][2] = dp[0][2];
for(int i=1; i<n; i++){
cnt[i][0] = Math.min(cnt[i-1][1], cnt[i-1][2]) + dp[i][0];
cnt[i][1] = Math.min(cnt[i-1][0], cnt[i-1][2]) + dp[i][1];
cnt[i][2] = Math.min(cnt[i-1][0], cnt[i-1][1]) + dp[i][2];
}
sb.append(Math.min(Math.min(cnt[n-1][0], cnt[n-1][1]), cnt[n-1][2]));
System.out.println(sb);
}
}