第一行输入一个整数
代表气球数量。
第二行输入一个长度为
的、仅由
构成的字符串代表气球的初始颜色。其中,
分别代表初始颜色为红、黄、蓝。
第三行输入
个整数
代表气球重新染色需要的时间。
在一行上输出一个整数,代表最少需要的染色时间。
5 00000 1 2 3 4 5
0
由于初始时全部气球颜色都是一样的,所以不需要重新进行染色。
6 210102 1 1 4 5 1 4
3
其中一种最优的染色方案是将气球染色为
,花费
。
6 001012 1 1 4 5 1 4
3
其中一种最优的染色方案是将气球染色为
,花费
。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int total = Integer.valueOf(in.nextLine());
String str = in.nextLine();
int[] weight = new int[total];
for (int i = 0; i < total; i++) {
weight[i] = in.nextInt();
}
if (str.matches("[0]+") || str.matches("[1]+") || str.matches("[2]+")) {
System.out.println(0);
return;
}
int result = -1;
for (int i = 1; i < total; i++) {
for (int j = i + 1; j < total; j++) {
int result1 = dfs(str, 0, i, weight);
int result2 = dfs(str, i, j, weight);
int result3 = dfs(str, j, total, weight);
int sum = result1 + result2 + result3;
result = result == -1 ? sum : Math.min(result, sum);
}
}
System.out.println(result);
}
static Map<String, Integer> map = new LinkedHashMap<>();
public static int dfs(String input, int x, int y, int[] weight) {
if (map.containsKey(x + ":" + y)) {
return map.get(x + ":" + y);
}
int result0 = 0;
int result1 = 0;
int result2 = 0;
for (int i = x; i < y; i++) {
char ch = input.charAt(i);
// 改成0
if (ch != '0') {
result0 += weight[i];
}
// 改成1
if (ch != '1') {
result1 += weight[i];
}
// 改成2
if (ch != '2') {
result2 += weight[i];
}
}
int min = Math.min(Math.min(result0, result1), result2);
map.put(x + ":" + y, min);
return min;
}