算法导论-15.5-4

Exercises 15.5-4

   Knuth has shown that there are always roots of optimal subtrees such that root[i,j-1]<=root[i,j]<=root[i+1,j] for all 1<=i<=n. Use this fact to modify the OPTIMAL-BST procedure to run in Θ(n^2) time.

——————————————————————————————————————————————————

  First prove this fact. Consider the optimal BST T[i+1,j] which has nodes from i+1 to j. Inserting a i node to T(i.e. i as i+1's left child, and proper adjustment to dummy nodes) makes also a legal BST T'[i,j]. If i+1's height is h, adding a i node leads to an increase of search cost by (h+1)*p[i]+(h+2)*q[i-1]+q[i]. When constructing the optimal BST T[i,j], if root[i,j] > root[i+1,j], then root[i+1,j](in T[i,j]) must appear in the root[i,j]'s left subtree. Since i+1's depth, with respective to root[i+1,j] in T[i,j] is identical to that in T[i+1,j]. The actual i's depth, i.e. with respective to T[i,j]'s root, root[i,j], is thus larger. But, we have another optimal tree T[i,j], which as a less increasing cost when inserting node i. Thus, T[i+1,j] plus node i-1 can make a better tree, which contradicts T[i,j]'s optimism. Therefore, root[i,j]<=root[i+1,j]. Similarly, root[i,j-1]<=root[i,j].

  Thus, we can modify the formula to e[i,j] = min{root[i,j-1]<=r<=root[i+1,j],e[i,r-1]+e[r+1,j]+w(i,j)}. Then we're to prove that the calculating of this formula, using dynamic programming, takes Θ(n^2) time. we call the group of states e[i,j] with the fixed j-i (=k) the level-k group(obviously there're n-k nodes in the group). the calculation of e[i,j] takes root[i+1,j]-root[i,j-1]+1 iterations. thus, for all level-k group states, their calculations takes root[k,1]-root[1,k]+n-k iterations in all. Since 1<=root[k,1],root[1,k]<=n, the number of iterations is thus Θ(n). And the k varies from 0 to n-1. Thus the overall complexity is Θ(n)*n = Θ(n^2). This is a common trick to optimize a Θ(n^3) dp algorithm for some kind of problems into a Θ(n^2) one.

具体实现:

第九行替换为:

if  i=j

root[i,j]
<-j

e[i,j]
<-pi+qi-1+qj

else for r<-root[i,j-1] to root[i+1,j]

你可能感兴趣的:(算法导论)