0% found this document useful (0 votes)
2 views

dsa practical 11

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.

Uploaded by

karan.ppjgk22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

dsa practical 11

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.

Uploaded by

karan.ppjgk22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Q.

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];

if (total < cost[i][j]) {


cost[i][j] = total;
}
}
}
}
return cost[1][n];
}
int main() {
vector<float> probabilities = {0.4, 0.2, 0.4};
int n = probabilities.size();
float minCost = optimalBST(probabilities, n);
cout << fixed << setprecision(2);
cout << "Minimum cost of Optimal BST: " << minCost << endl;
return 0;
}

Input: -

Output: -

You might also like