-
Notifications
You must be signed in to change notification settings - Fork 77
/
optimal_search_tree.cpp
66 lines (58 loc) · 2 KB
/
optimal_search_tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#define MAX 1000
int sum[MAX];
/* A Dynamic Programming based function that calculates minimum cost of
a Binary Search Tree. */
int optimalSearchTree(int keys[], int freq[], int n) {
/* Create an auxiliary 2D matrix to store results of subproblems */
int cost[n][n];
/* cost[i][j] = Optimal cost of binary search tree that can be
formed from keys[i] to keys[j].
cost[0][n-1] will store the resultant cost */
// For a single key, cost is equal to frequency of the key
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];
// Now we need to consider chains of length 2, 3, ... .
// L is chain length.
for (int L = 2; L <= n; L++) {
// i is row number in cost[][]
for (int i = 0; i <= n - L + 1; i++) {
// Get column number j from row number i and chain length L
int j = i + L - 1;
cost[i][j] = INT_MAX;
// Try making all keys in interval keys[i..j] as root
for (int r = i; r <= j; r++) {
// c = cost when keys[r] becomes root of this subtree
int c = ((r > i) ? cost[i][r - 1] : 0) +
((r < j) ? cost[r + 1][j] : 0) +
sum[j] - sum[i - 1];
if (c < cost[i][j]) {
cost[i][j] = c;
//printf("%d %d %d\n", i, j, keys[r]);
}
}
}
}
#if 0
// print the cost matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(i <= j) printf("%6d", cost[i][j]);
else printf(" ");
}
printf("\n");
}
#endif
return cost[0][n - 1];
}
// Driver program to test above functions
int main() {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
// precalculating sum
for (int i = 0; i < n; i++) {
sum[i] = sum[i - 1] + freq[i];
}
printf("Cost: %d\n", optimalSearchTree(keys, freq, n));
return 0;
}