算法导论15.5 最优二叉查找树

//15.5最优二叉查找树
# include<iostream>
using namespace std;

#define N 5
double e[N+2][N+2]={0},w[N+2][N+2]={0};
int root[N+2][N+2]={0};

void Optimal_Bst(double p[],double q[],int n)//
{
	int i,j,l,r;
	double t;
	for(i=1;i<=n+1;++i)
	{
		e[i][i-1]=q[i-1];
		w[i][i-1]=q[i-1];
	}
	for(l=1;l<=n;l++)
	{
		for(i=1;i<=n-l+1;i++)
		{
			j=i+l-1;
			e[i][j]=0x7fffffff;
			w[i][j]=w[i][j-1]+p[j]+q[j];
			for(r=i;r<=j;r++)
			{
				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;
				}
			}
		}
	}
}

void Construct_Optimal_Tree(int start,int end)
{
	int r=root[start][end];
	if(r-1<start)
		cout<<'d'<<r-1<<" is k"<<r<<"'s left child"<<endl;
	else
	{
		cout<<'k'<<root[start][r-1]<<" is k"<<r<<"'s left child"<<endl;
		Construct_Optimal_Tree(start,r-1);
	}
	 if(end < r+1)  
        cout<<'d'<<end<<" is k"<<r<<"'s right child"<<endl;    
    else  
    {  
        cout<<'k'<<root[r+1][end]<<" is k"<<r<<"'s right child"<<endl;  
        Construct_Optimal_Tree(r+1, end);  
    }  
}  

void main()
{
	double p[6]={0,0.15,0.10,0.05,0.10,0.20};
	double q[6]={0.05,0.10,0.05,0.05,0.05,0.10};
	Optimal_Bst(p,q,N);
	cout<<'k'<<root[1][N]<<" is root"<<endl;
	Construct_Optimal_Tree(1,N);
}


    原文作者:查找算法
    原文地址: https://blog.csdn.net/eh_in_our_times/article/details/11556795
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞