简体   繁体   中英

Knuth's Optimal Binary Search tree in O(n^2)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM