|
| 1 | +# Copyright (c) June 02, 2017 CareerMonk Publications and others. |
| 2 | + |
| 3 | +# Creation Date : 2017-06-02 06:15:46 |
| 4 | +# Last modification : 2017-06-02 |
| 5 | +# Modified by : Narasimha Karumanchi |
| 6 | +# Book Title : Algorithm Design Techniques |
| 7 | +# Warranty : This software is provided "as is" without any |
| 8 | +# warranty; without even the implied warranty of |
| 9 | +# merchantability or fitness for a particular purpose. |
| 10 | + |
| 11 | +def OBST(A, F, get_bst=False): |
| 12 | + n = len(A) |
| 13 | + table = [[None] * n for _ in xrange(n)] |
| 14 | + for i in xrange(n): |
| 15 | + table[i][i] = (F[i], i) |
| 16 | + # let optimal BST for subproblem A[i..j] be T |
| 17 | + # if table[i][j] = (cost, keyidx) |
| 18 | + # then cost is the cost of T, keyidx is index of the root key of T |
| 19 | + for s in xrange(1, n): |
| 20 | + for i in xrange(n-s): |
| 21 | + # compute cost for A[i..i+s] |
| 22 | + minimal, root = float('inf'), -1 |
| 23 | + # search root with minimal cost |
| 24 | + freq_sum = sum(F[x] for x in xrange(i, i+s+1)) |
| 25 | + for r in xrange(i, i+s+1): |
| 26 | + left = 0 if r == i else table[i][r-1][0] |
| 27 | + right = 0 if r == i+s else table[r+1][i+s][0] |
| 28 | + cost = left + right + freq_sum |
| 29 | + if cost < minimal: |
| 30 | + minimal = cost |
| 31 | + root = r |
| 32 | + table[i][i+s] = (minimal, root) |
| 33 | + if get_bst: |
| 34 | + tree = {} |
| 35 | + stack = [(0, n-1)] |
| 36 | + while stack: |
| 37 | + i, j = stack.pop() |
| 38 | + root = table[i][j][1] |
| 39 | + left, right = None, None |
| 40 | + if root != i: |
| 41 | + stack.append((i, root-1)) |
| 42 | + left = table[i][root-1][1] |
| 43 | + if root != j: |
| 44 | + stack.append((root+1, j)) |
| 45 | + right = table[root+1][j][1] |
| 46 | + if left is None and right is None: |
| 47 | + tree[root] = None |
| 48 | + else: |
| 49 | + tree[root] = (left, right) |
| 50 | + return (table[0][n-1][0], tree) |
| 51 | + |
| 52 | + return table[0][n-1][0] |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + assert OBST([0, 1], [30, 40]) == 100 |
| 56 | + assert OBST(['a', 'b', 'c'], [30, 10, 40]) == 130 |
| 57 | + assert OBST([0, 1], [0.6, 0.4]) == 1.4 |
| 58 | + assert OBST(range(1, 8), [0.05, 0.4, 0.08, 0.04, 0.1, 0.1, 0.23]) == 2.18 |
0 commit comments