java实现:
public class 最优二叉搜索树问题 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double p[] = {0,0.15,0.10,0.05,0.10,0.20};
double q[] = {0.05,0.10,0.05,0.05,0.05,0.10};
double p1[] = {0,0.04,0.06,0.08,0.02,0.10,0.12,0.14};
double q1[] = {0.06,0.06,0.06,0.06,0.05,0.05,0.05,0.05};
Optimal_BST(p, q, p.length-1);
System.out.println();
Optimal_BST(p1, q1, p1.length-1);
}
public static void Optimal_BST(double p[], double q[],int n) {
double e[][] = new double[n+2][n+1];
double w[][] = new double[n+2][n+1];
int root[][] = new int[n+1][n+1];
for(int i = 1; i<= n+1; i++) {
e[i][i-1] = q[i-1];
w[i][i-1] = q[i-1];
}
for(int l = 1; l <= n; l++) {
for(int i = 1; i<= n-l+1; i++) {
int j = i+l-1;
e[i][j] = 1e9;
w[i][j] = w[i][j-1] + p[j] + q[j];
for(int r = i; r<=j; r++) {
double t = e[i][r-1] + e[r+1][j] + w[i][j];
if(t < e[i][j]) {
e[i][j] = t;
root[i][j] = r;
}
}
}
}
System.out.println(e[1][n]);
construct_optimal_BST(root, 1, n);
}
// 打印树根
public static void construct_optimal_BST(int root[][], int i, int j) {
if(i>j || root[i][j] == 0) {
return ;
}
else {
int r = root[i][j];
System.out.print(r+" ");
construct_optimal_BST(root, i, r-1);
construct_optimal_BST(root, r+1, j);
}
}
}