0

I am trying to implement Knuth's optimal binary search tree which can run in O(n^2) time. I have the code which is running in O(n^3).

float P[N + 1] = {0, .13, .12, .15, .05, .12, .10, .08, .09, .03, .13};
float sum[N + 1] = {0, .13, .25, .40, .45, .57, .67, .75, .84, .87, 1.00};
float M[N + 1][N + 1];
int root[N + 1][N + 1];
int s, i, j;
float temp;
for (s = 0; s <= N; s++){
    for (i = 0; i <= N; i++){
        M[s][i] = 0;
        root[s][i] = 0;

    }

}
for (s = 2; s <= N; s++){
    for (i = 1; i <= N - s + 1; i++){
        M[s][i] = N;
        for (j = i; j <= i + s - 1; j++){
            temp = M[j - i][i] + M[i + s - j - 1][j + 1]+ sum[i + s - 1] - sum[i - 1] - P[j];
            if (M[s][i] > temp){
                M[s][i] = temp;
                root[s][i] = j;

            }

        }

    }
}

M is the array of costs. P is the probability of each node. I get some ideas from: Dynamic Programming: Why Knuth's improvement to Optimal Binary Search Tree O(n^2)?. In my case, I tried to modify the third loop from for (j = i; j <= i + s - 1; j++) to for (j = root[s+1][i]; j <= root[s][i-1]; j++). But it doesn't work. Could someone give me some clue on this problem?

Slim
  • 13
  • 4

1 Answers1

0

You're supposed to be computing the costs of the optimal subtrees in non-decreasing order by size, so when you're filling in M[s][i] --- the minimum cost of a subtree of size s whose leftmost key has index i --- you haven't filled in M[s+1][i] or root[s+1][i] yet.

Cheers, Travis

PS "j <= root[s][i-1]" isn't quite right either.

  • I figure out the lower bound of j. But in this code, it seems we only add nodes to the right of the root. So could you give me some hint about the upper bound? – Slim Jun 18 '20 at 23:33
  • You're close, but your array indices are off. Check the last 5 minutes of [link](https://dal.brightspace.com/d2l/le/content/124045/viewContent/1721462/View) (but remember k is related to s but isn't the same thing). – Travis Gagie Jun 19 '20 at 01:39
  • I get it. Upper bound should be kind of last-next, haha – Slim Jun 19 '20 at 02:38