Problem Statement: Given a sorted array key [0.. n-1] of search keys and an array freq[0….n-1] of frequency counts, where freq[i] is the number of searches for keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible.
This problem can be solved by applying Dynamic Programming.
#include <bits/stdc++.h> using namespace std; int sum(int freq[], int i, int j); int optimalSearchTree(int keys[], int freq[], int n) { int cost[n][n]; for (int i = 0; i < n; i++) cost[i][i] = freq[i]; for (int L = 2; L <= n; L++) { for (int i = 0; i <= n-L+1; i++) { int j = i+L-1; cost[i][j] = INT_MAX; for (int r = i; r <= j; r++) { int c = ((r > i)? cost[i][r-1]:0) + ((r < j)? cost[r+1][j]:0) + sum(freq, i, j); if (c < cost[i][j]) cost[i][j] = c; } } } return cost[0][n-1]; } int sum(int freq[], int i, int j) { int s = 0; for (int k = i; k <= j; k++) s += freq[k]; return s; } int main() { int keys[] = {10, 12, 20}; int freq[] = {34, 8, 50}; int n = sizeof(keys)/sizeof(keys[0]); cout << "Cost of Optimal BST is " << optimalSearchTree(keys, freq, n); return 0; }
Optimization of this program:-
Time Complexity:- O(n^4)
Output of this Program should be:- 142