The document presents a C++ implementation for constructing an optimal binary search tree (BST) based on given search probabilities for sorted keys. It defines a function 'optimalBST' that calculates the minimum search cost using dynamic programming. The main function demonstrates the use of this function with a sample set of probabilities, outputting the minimum cost of the optimal BST.
The document presents a C++ implementation for constructing an optimal binary search tree (BST) based on given search probabilities for sorted keys. It defines a function 'optimalBST' that calculates the minimum search cost using dynamic programming. The main function demonstrates the use of this function with a sample set of probabilities, outputting the minimum cost of the optimal BST.
Given sequence k = k1 <k2 < … <kn of n sorted keys, with a search
probability pi for each key ki. Build the Binary search tree that has the least search cost given the access Probability for each key? #include <iostream> #include <vector> #include <iomanip> #include <climits> using namespace std; float optimalBST(const vector<float>& p, int n) { vector<vector<float>> cost(n + 2, vector<float>(n + 1, 0)); vector<vector<float>> sum(n + 2, vector<float>(n + 1, 0)); for (int i = 1; i <= n; ++i) { cost[i][i] = p[i - 1]; sum[i][i] = p[i - 1]; } for (int L = 2; L <= n; ++L) { for (int i = 1; i <= n - L + 1; ++i) { int j = i + L - 1; cost[i][j] = FLT_MAX; sum[i][j] = sum[i][j - 1] + p[j - 1]; for (int r = i; r <= j; ++r) { float left = (r > i) ? cost[i][r - 1] : 0; float right = (r < j) ? cost[r + 1][j] : 0; float total = left + right + sum[i][j];