public class MNset {
public static void mnset(int[] c, int[][] size) {
int n = c.length - 1;
for (int j = 0; j < c[1]; j++) {
size[1][j] = 0; // 下面没有接线柱的时候,都为0
}
for (int j = c[1]; j <= n; j++) {
size[1][j] = 1; // 有且一根接线柱连上,后面的也是一根
}
for (int i = 2; i <= n; i++) { // 超过两根接线柱的时候
for (int j = 0; j < c[i]; j++) {
size[i][j] = size[i - 1][j]; // 往上看,因为这根线还没连上
}
for (int j = c[i]; j <= n; j++) {// 连上了,看看要还是不要
size[i][j] = Math.max(size[i - 1][j],size[i - 1][c[i] - 1] + 1);
}
}
// 最后返回
size[n][n] = Math.max(size[n - 1][n],size[n - 1][c[n] - 1] + 1);
}
// 构造最优解
public static int traceback(int[] c, int[][] size, int[] net) {
int n = c.length - 1;
int j = n;
int m = 0;
for (int i = n; i > 1; i--) {
if (size[i][j] != size[i - 1][j]) {
net[m++] = i;
j = c[i] - 1;
}
if (j >= c[i])
net[m++] = 0;
}
return m;
}
public static void main(String[] args) {
int[] c = {0,6,8,12,2,1,4,5,3,11,7,10,9,13};
int[][] size = new int[c.length][c.length];
MNset.mnset(c,size);
System.out.println(Arrays.toString(size[0]));
System.out.println(Arrays.toString(size[1]));
System.out.println(Arrays.toString(size[2]));
System.out.println(Arrays.toString(size[3]));
System.out.println(Arrays.toString(size[4]));
System.out.println(Arrays.toString(size[5]));
System.out.println(Arrays.toString(size[6]));
System.out.println(Arrays.toString(size[7]));
System.out.println(Arrays.toString(size[8]));
System.out.println(Arrays.toString(size[9]));
System.out.println(Arrays.toString(size[10]));
System.out.println(Arrays.toString(size[11]));
System.out.println(Arrays.toString(size[12]));
System.out.println(Arrays.toString(size[13]));
int[] net = new int[c.length];
MNset.traceback(c, size, net);
System.out.println("------------result---------------");
System.out.println(Arrays.toString(net));
}
}
(动态规划)电路布线问题
最新推荐文章于 2023-10-11 20:46:43 发布