算法参考算法导论第二版——最优搜索树
#include<iostream>
#define EType int
#define MAX numeric_limits<double>::max()
using namespace std;
void Construct_Optimal_BST(int **root,int i,int j,bool flag);
void OPTIMAL_BST(double p[],double q[], int n)
{
double **e,**w;
int **root;
e = new double*[n+2];
w = new double*[n+2];
e[0] = new double[(n+2)*(n+2)];
w[0] = new double[(n+2)*(n+2)];
root = new int*[n+1];
root[0] = new int[(n+1)*(n+1)];
for(int i = 1; i < n+2; ++i)
{
e[i][i-1] = q[i-1];
w[i][i-1] = q[i-1];
e[0][i-1] = 0;
w[0][i-1] = 0;
}
for(int i = 1; i< (n+2); ++i)
for(int j = 1; j< (n+2); ++j)
root[i][j] = 0;
for(int l = 1; l<=n; ++l)
for(int i = 1; i <= n-l+1; )
{
int j = i+l-1;
e[i][j] = MAX;
w[i][j] = w[i][j-1] + p[j] + q[j];
for(int r = i; r<= j; ++r)
{
int 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;
}
}
}
Construct_Optimal_BST(root,1,n,false);
}
void Construct_Optimal_BST(int **root,int i,int j,bool flag)
{
if(flag==0)
{
cout<<"k"<<root[i][j]<<" 是根"<<endl;
flag=1;
}
int r=root[i][j];
//如果左子树是叶子
if(r-1<i)
{
cout<<"d"<<r-1<<" is the left child of "<<"K"<<r<<endl;
}
//如果左子树不是叶子
else
{
cout<<"k"<<root[i][r-1]<<" is the left child of "<<"K"<<r<<endl;
Construct_Optimal_BST(root,i,r-1,1);
}
//如果右子树是叶子
if(r>=j)
{
cout<<"d"<<j<<" is the right child of "<<"K"<<r<<endl;
}
//如果右子树不是叶子
else
{
cout<<"k"<<root[r+1][j]<<" is the right child of "<<"K"<<r<<endl;
Construct_Optimal_BST(root,r+1,j,1);
}
}