Question

In: Computer Science

An OBST (optimal BST) minimizes the average search time across all keys in the BST. Given...

  1. An OBST (optimal BST) minimizes the average search time across all keys in the BST. Given 5 ordered keys. k1<k2<k3<k4<k5, with probabilities of occurrence (0.25, 0.15, 0.10, 0.20, 0.30), respectively
    1. Use a Greedy algorithm that attempts to construct a BST that is an OBST.
    2. What is the complexity of your Greedy algorithm?  
    3. Is your Greedy BST an OBST? Explain
    4. apply the DP algorithm to acquire an OBST
    5. show your work, including tables and the extraction of the actual OBST
    6. analyze the complexity of the DP algorithm

Solutions

Expert Solution

// A naive recursive implementation of  
// optimal binary search tree problem  
#include <bits/stdc++.h> 
using namespace std; 
  
// A utility function to get sum of  
// array elements freq[i] to freq[j]  
int sum(int freq[], int i, int j);  
  
// A recursive function to calculate  
// cost of optimal binary search tree  
int optCost(int freq[], int i, int j)  
{  
    // Base cases  
    if (j < i)  // no elements in this subarray  
        return 0;  
    if (j == i) // one element in this subarray  
        return freq[i];  
      
    // Get sum of freq[i], freq[i+1], ... freq[j]  
    int fsum = sum(freq, i, j);  
      
    // Initialize minimum value  
    int min = INT_MAX;  
      
    // One by one consider all elements  
    // as root and recursively find cost  
    // of the BST, compare the cost with 
    // min and update min if needed  
    for (int r = i; r <= j; ++r)  
    {  
        int cost = optCost(freq, i, r - 1) +  
                   optCost(freq, r + 1, j);  
        if (cost < min)  
            min = cost;  
    }  
      
    // Return minimum value  
    return min + fsum;  
}  
  
// The main function that calculates  
// minimum cost of a Binary Search Tree.  
// It mainly uses optCost() to find  
// the optimal cost.  
int optimalSearchTree(int keys[],  
                      int freq[], int n)  
{  
    // Here array keys[] is assumed to be  
    // sorted in increasing order. If keys[]  
    // is not sorted, then add code to sort  
    // keys, and rearrange freq[] accordingly.  
    return optCost(freq, 0, n - 1);  
}  
  
// A utility function to get sum of  
// array elements freq[i] to freq[j]  
int sum(int freq[], int i, int j)  
{  
    int s = 0;  
    for (int k = i; k <= j; k++)  
    s += freq[k];  
    return s;  
}  
  
// Driver Code 
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;  
}  

Here is the dp approach

// Dynamic Programming code for Optimal Binary Search 
// Tree Problem 
#include <bits/stdc++.h> 
using namespace std; 

// A utility function to get sum of array elements 
// freq[i] to freq[j] 
int sum(int freq[], int i, int j); 

/* 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(freq, i, j); 
                        if (c < cost[i][j]) 
                                cost[i][j] = c; 
                        } 
                } 
        } 
        return cost[0][n-1]; 
} 

// A utility function to get sum of array elements 
// freq[i] to freq[j] 
int sum(int freq[], int i, int j) 
{ 
        int s = 0; 
        for (int k = i; k <= j; k++) 
        s += freq[k]; 
        return s; 
} 

// Driver code 
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; 
} 

Related Solutions

I was trying to implement a simple binary search tree using this given class of bst...
I was trying to implement a simple binary search tree using this given class of bst in c++ public: BST(); ~BST(); void insertKey(int newKey); bool hasKey(int searchKey); std::vector<int> inOrder(); int getHeight(); however; i am still required to use another class for the nodes as a pointer and i need to manage memory leak. in main we should ask for the numbers we need to insert in the binary search tree and also let the user end it with a letter...
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Given a binary search tree T with n elements. For any two keys k1 and k2...
Given a binary search tree T with n elements. For any two keys k1 and k2 such that k1 < k2, there is an algorithm to print all elements x in T such that k1 ≤x ≤k2 in O(K + log n) time on average, where K is the number of the elements printed out.
Determine the optimal dynamic allocation of a nonrenewable resource across two time periods based on the...
Determine the optimal dynamic allocation of a nonrenewable resource across two time periods based on the information provided. Your answer should include: MNB1 MNB2 PV(MNB2) The optimal quantity of consumption in period one The optimal quantity of consumption in period two, and a detailed presentation of HOW you derived your answers.                                                          Period One                              Period Two Demand schedules:             PD1 = 100 - 0.4Q1                    PD2 = 160 - 0.5Q2          Supply schedules:                PS1 = 20 + 0.2Q1                     PS2 =...
1. What is the Big-O run-time of linear search and binary search in the best, average...
1. What is the Big-O run-time of linear search and binary search in the best, average and worst cases?       Linear Search                  Binary Search Best: Worst: Average: 2. What is the Big-O runtime of the following linked list methods? addFirst() toString() What is the Big-O runtime of the below Stack method? isSorted(Node n) 3. What is the Big-O runtime of the below methods: Method A: Stack Copy Constructor Option 1 public Stack(Stack<T> original) { if(original == null) { return; }...
What is the Average time complexity of sequential search algorithm in a linked list?
What is the Average time complexity of sequential search algorithm in a linked list?
Show that if P=NP then there is a polynomial-time algorithm for the following search problem: given...
Show that if P=NP then there is a polynomial-time algorithm for the following search problem: given a graph, find its largest clique.
The total trading taken place in a given stock for a day across all exchanges is...
The total trading taken place in a given stock for a day across all exchanges is referred to as:             A) block trading B) composite trading C) total trades D) margin trading 3) Each of the following are required for a corporation to pay a cash dividend except for:          sufficient retained earnings    a vote by managers    declaration by the board of directors sufficient cash to pay the dividend             . 4) The risk of consumers losing purchasing...
After all the time, effort and care you put into your work search, it can be...
After all the time, effort and care you put into your work search, it can be tempting to leap at the first job you’re offered without negotiating salary, benefits and other terms of employment. With the exception of some entry-level positions and jobs where you’re automatically placed on a grid determined by education and experience, many employers expect you to make a counter- offer and negotiate terms. To effectively negotiate a job offer, you need to understand and evaluate the...
Given the array a and the binary search function below, list all ACTIVATIONS IN FINDING t=19....
Given the array a and the binary search function below, list all ACTIVATIONS IN FINDING t=19. (15 Points) -9 -5 -2 0 1 3 7 11 17 19 21 25 27 31 37 41 a    index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 int search(int a[], int t, int l, int r){ if(l<=r){ int m=(l+r)/2; if(t==a[m]) return m; else if (t<a[m]) return search(a, t, l,m-1); else return search(a, t, m+1,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT