Optimal binary search tree, dynamic programming, two-dimensional table, table filling optimization, code

    The author first introduces the optimal binary search tree of the dynamic programming method and the table filling formula (essentially, I want to complain about its cumbersomeness).

    Let T(i, j) be a binary search tree consisting of records {ri, …, rj} (1≤i≤j≤n), and C(i, j) be the average number of comparisons in this binary search tree . Although the final result is C(1, n), following the dynamic programming method, it is necessary to find the value of all smaller sub-problems C(i, j), consider choosing one from {ri, ..., rj} Recording rk as the root node of the binary search tree, the following relationship can be obtained:

    Let a two-dimensional table C[n+1][n+1], where C[i][j] represents the average number of comparisons of the binary search tree T(i, j). The two-dimensional table R[n+1][n+1] has the same subscript range as the two-dimensional table C, and R[i][j] represents the sequence number of the root node of the binary search tree T(i, j) .

    If you want to get the values ​​of two two-dimensional tables, you need to calculate each C[i][j] according to the formula, which is fatal to people who hate cumbersome things like the author, so I try to find the rules in the table, Fantasy does not use formulas, but can quickly find accurate values. Facts have proved that the law exists.

When finding C[i][j], set the hypotenuse     of a right triangle formed by three points C[i][i-1], C[j+1][j], C[i][j] The cumulative sum of the values ​​above is S (oblique), and the sum of the corresponding two points on the right-angled side is S (straight). Obviously, there are j-i+1 S[straight], then C[i][j]=S[oblique] ]+min{S[straight]}. Let's take an example to find the value of C[1][3], as shown in the figure:

    S(oblique)=0.1+0.2+0.4=0.7, S(straight)=min{S1(straight), S2(straight), S3(straight)}=min{0+0.8,0.1+0.4,0.4+0} =0.4, then C[1][3]=0.7+0.4=1.1. In the same way, find C[2][4], as shown in the figure below, C[2][4]=1.4:

    In fact, the essence has not changed, but the mathematical formulas are graphically displayed to facilitate filling in forms. The optimal binary search tree code is as follows:

void OptimalBST(double a[],double b[],int n,double **R,int **mink,double **C)
{
	//initialization
	for(int i=0; i<=n; i++)
	{
		C[i+1][i] = a[i];
		R[i+1][i] = 0;
	}
	for(int d=0; d<n; d++)
		for(int i=1; i<=nd; i++) //calculate the diagonal line by line
		{
			C[i][j]=C[i][j-1]+a[j]+b[j];
			R[i][j]=R[i+1][j];
			mink[i][j]=i;
			for(int k=i+1; k<=j; k++)
				if(R[i][k-1]+R[k+1][j]<R[i][j])
				{
					R[i][j]= R[i][k-1]+R[k+1][j];
					mink[i][j]=k;
				}
			R[i][j]+=C[i][j];
		}
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326045561&siteId=291194637