[PS] RGB거리 (백준 1148번)
쉬운 편에 속하는 DP 문제인 것 같은데, 아주 아주 약간(?)의 발상이 필요한 문제였다.
필기를 통해 충분히 계산하고 코드 작성을 시작하자!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/* BOJ no.1149 - RGB거리 (DP) */
public class Main {
static int N;
static int[] costOfLastRed = new int[1001];
static int[] costOfLastGreen = new int[1001];
static int[] costOfLastBlue = new int[1001];
static int totalCost;
public static void main(String[] args) {
inputAndCalculate();
printResult();
}
static void printResult() {
System.out.println(totalCost);
}
static void inputAndCalculate() {
Reader reader = new Reader();
N = reader.readInt();
int size = N+1;
int redCostOfIdx = 0;
int greenCostOfIdx = 0;
int blueCostOfIdx = 0;
int beforeIdx = -1;
for (int idx = 1; idx < size; idx++) {
if (idx == 1) {
costOfLastRed[idx] = reader.readInt();
costOfLastGreen[idx] = reader.readInt();
costOfLastBlue[idx] = reader.readInt();
continue;
}
beforeIdx = idx - 1;
redCostOfIdx = reader.readInt();
greenCostOfIdx = reader.readInt();
blueCostOfIdx = reader.readInt();
costOfLastRed[idx] = Math.min(costOfLastGreen[beforeIdx] + redCostOfIdx, costOfLastBlue[beforeIdx] + redCostOfIdx);
costOfLastGreen[idx] = Math.min(costOfLastBlue[beforeIdx] + greenCostOfIdx, costOfLastRed[beforeIdx] + greenCostOfIdx);
costOfLastBlue[idx] = Math.min(costOfLastRed[beforeIdx] + blueCostOfIdx, costOfLastGreen[beforeIdx] + blueCostOfIdx);
}
totalCost = Math.min(costOfLastRed[N], costOfLastGreen[N]);
totalCost = Math.min(totalCost, costOfLastBlue[N]);
}
static class Reader {
static BufferedReader bufferedReader;
static StringTokenizer stringTokenizer;
Reader() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
String read() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
int readInt() {
return Integer.parseInt(read());
}
}
}
부족한 점이나 피드백은 사랑입니다 :)