空间效率O(n2),时间效率O(n3)
当1<=i<=j<=n时,C[i,j]=min(i<=k<=j){C[i,k-1]+C[k+1,j]}+(pi+……+pj)
public class OptimalBST {
private int nodeNum = 4;
private int[][] R;
private double[][] C;
private double[] p;
public OptimalBST(int nodeNum, double[] a) {
super();
this.nodeNum = nodeNum;
p=new double[nodeNum];
for (int i = 0; i < a.length; i++)
this.p[i] = a[i];
R = new int[nodeNum + 2][nodeNum + 1];
C = new double[nodeNum + 2][nodeNum + 1];
}
public void optimalBST() {
for (int i = 1; i <= nodeNum; i++) {
C[i][i - 1] = 0;
C[i][i] = p[i-1];
R[i][i] = i;
}
C[nodeNum + 1][nodeNum] = 0;
int d = 0, i = 0, j = 0, k = 0, kmin = 0;
double minval = 0.0, sum = 0.0;
for (d = 1; d <= nodeNum - 1; d++)
// 对角线计数
for (i = 1; i <= nodeNum - d; i++) {
j = i + d;
minval = 999; //无穷大这里用999代替
for (k = i; k <= j; k++) {
if (C[i][k - 1] + C[k + 1][j] < minval) {
minval = C[i][k - 1] + C[k + 1][j];
kmin = k;
}
}
R[i][j] = kmin;
sum = p[i-1];
for (int s = i; s < j; s++)
sum += p[s];
C[i][j] = minval + sum;
}
}
public void showCR() {
for (int i = 0; i < nodeNum+2; i++) {
for (int j = 0; j < nodeNum+1; j++)
System.out.print(C[i][j] + " ");
System.out.println();
}
for (int i = 0; i < nodeNum+2; i++) {
for (int j = 0; j < nodeNum+1; j++)
System.out.print(R[i][j] + " ");
System.out.println();
}
}
public static void main(String[] argv) {
double[] p = new double[] { 0.1, 0.2, 0.4, 0.3 };
OptimalBST optimalBST=new OptimalBST(4, p);
optimalBST.optimalBST();
optimalBST.showCR();
}
}