//输入p: 访问概率数组; 0,1,....n是排好序的Key值
//输出A=new float[n][n]: 最优时间矩阵
//输出R=new int[n][n]: 根结点矩阵
static void optimalBST(float[] p,float[][] A,int[][] R){
int n = p.length;
for(int i=0;i<n;i++){
A[i][i] = p[i];
R[i][i] = i; //the root is itself
}
for(int diag=1;diag<n;diag++){
for(int i=0;i<n;i++){
int j = diag + i;
if(j>n-1) break;
float min=-1;
int root=i;
for(int k=i;k<=j;k++){
float tmp1 = 0;
float tmp2 = 0;
if(k-1>=i){
tmp1 = A[i][k-1];
}
if(j>=k+1){
tmp2 = A[k+1][j];
}
float tmp = tmp1 + tmp2;
//all min must be greater than 0.
if(min<0 || tmp<min){
min = tmp;
root = k;
}
}
R[i][j] = root;
A[i][j] = min;
for(int m=i;m<=j;m++){
A[i][j] += p[m];
}
}
}
}