SlideShare a Scribd company logo
Optimal Binary Search
DESIGN ANALYSIS AND ALGORITHM
CSE3004
What is the problem?
• Determining the cost and the structure of the Optimal Binary Search Tree
(OBST) for a set of 4 keys to find the smallest possible search time for a
given sequence of accesses.
INDEX 0 11 2 3
NODE 43 13 80 74
FREQUENCY 3 4 8 9
Algorithm
• Here, the Optimal Binary Search Tree Algorithm is presented.
• First, we build a BST from a set of provided n number of distinct keys < k1,
k2, k3, ... kn >.
• Here we assume, the probability of accessing a key Ki is pi.
• Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be
performed for the values which are not present in the Key set K.
• We assume, for each dummy key di probability of access is qi.
Algorithm
int sum(int freq[], int i, int j);
int optCost(int freq[], int i, int j)
{
if (j < i) // no elements in this subarray
return 0;
if (j == i)
return freq[i];
int fsum = sum(freq, i, j);
int min = INT_MAX;
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 min + fsum;
}
int optimalSearchTree(int keys[],
int freq[], int n) {
return optCost(freq, 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;
}
Solving the Problem
• First for l = 1
calculating costs of following
Cost[0,0] = 3
Cost[1,1] = 4
Cost[2,2] = 8
Cost[3,3] = 9
• Now for l = 2
calculating cost
Cost[0,1] = 10
Cost[1,2] = 16
Solving the Problem
• For l = 2
calculating cost
Cost[2,3] = 25
• Now for l = 3
calculating cost
Cost[0,2] = 25
Cost[1,3] = 34
• For l = 4
calculating cost
Cost[0,3] = 43 (Maximum frequency)
Calculating Minimum Frequency
From the matrix 43 is the maximum value
with node (2)
Now mention second node as a root
node, with all the other nodes as the child
nodes and the following optimal binary
search tree is formed
Checking frequency as per formed obst.
Total frequency = 8x1 + 3x2 + 9x2 + 4x3
= 9 + 16 + 18 + 12
= 43
Hence Verified.
THANK YOU
MADE BY –
A&C

More Related Content

What's hot (20)

N queen problem
N queen problemN queen problem
N queen problem
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithm
 
linear probing
linear probinglinear probing
linear probing
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Hashing
HashingHashing
Hashing
 
4 greedy methodnew
4 greedy methodnew4 greedy methodnew
4 greedy methodnew
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.
 
Hash table
Hash tableHash table
Hash table
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
 
Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
Big o notation
Big o notationBig o notation
Big o notation
 
Time complexity
Time complexityTime complexity
Time complexity
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Merge Sort
Merge SortMerge Sort
Merge Sort
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)
 

Similar to OPTIMAL BINARY SEARCH

14_OptimalBinarySearchTree.ppt
14_OptimalBinarySearchTree.ppt14_OptimalBinarySearchTree.ppt
14_OptimalBinarySearchTree.pptriyiko
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structureShakil Ahmed
 
Datastructure tree
Datastructure treeDatastructure tree
Datastructure treerantd
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexityshowkat27
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmRajKumar323561
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
OptimalBinarySearchTree.ppt
OptimalBinarySearchTree.pptOptimalBinarySearchTree.ppt
OptimalBinarySearchTree.pptFreeze16
 
Yoyak ScalaDays 2015
Yoyak ScalaDays 2015Yoyak ScalaDays 2015
Yoyak ScalaDays 2015ihji
 
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...garbervetsky
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysisDr. Rajdeep Chatterjee
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosluzenith_g
 

Similar to OPTIMAL BINARY SEARCH (20)

14_OptimalBinarySearchTree.ppt
14_OptimalBinarySearchTree.ppt14_OptimalBinarySearchTree.ppt
14_OptimalBinarySearchTree.ppt
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Datastructure tree
Datastructure treeDatastructure tree
Datastructure tree
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithm
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
OptimalBinarySearchTree.ppt
OptimalBinarySearchTree.pptOptimalBinarySearchTree.ppt
OptimalBinarySearchTree.ppt
 
Yoyak ScalaDays 2015
Yoyak ScalaDays 2015Yoyak ScalaDays 2015
Yoyak ScalaDays 2015
 
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
ByteCode 2012 Talk: Quantitative analysis of Java/.Net like programs to under...
 
Codes and Isogenies
Codes and IsogeniesCodes and Isogenies
Codes and Isogenies
 
Lec39
Lec39Lec39
Lec39
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmos
 
Alg1
Alg1Alg1
Alg1
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 

More from Cool Guy

Module 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsModule 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsCool Guy
 
Modified Distribution Method (MODI)
Modified Distribution Method (MODI)Modified Distribution Method (MODI)
Modified Distribution Method (MODI)Cool Guy
 
Class 12 Maths Board Syllabus CBSE 2018
Class 12 Maths Board Syllabus CBSE 2018Class 12 Maths Board Syllabus CBSE 2018
Class 12 Maths Board Syllabus CBSE 2018Cool Guy
 
Criminal Record System
Criminal Record SystemCriminal Record System
Criminal Record SystemCool Guy
 
Infrared Security System
Infrared Security SystemInfrared Security System
Infrared Security SystemCool Guy
 
The Preparation Of Potash Alum
The Preparation Of Potash AlumThe Preparation Of Potash Alum
The Preparation Of Potash AlumCool Guy
 
Soil pollution
Soil pollutionSoil pollution
Soil pollutionCool Guy
 
Software concepts
Software conceptsSoftware concepts
Software conceptsCool Guy
 

More from Cool Guy (8)

Module 2 Design Analysis and Algorithms
Module 2 Design Analysis and AlgorithmsModule 2 Design Analysis and Algorithms
Module 2 Design Analysis and Algorithms
 
Modified Distribution Method (MODI)
Modified Distribution Method (MODI)Modified Distribution Method (MODI)
Modified Distribution Method (MODI)
 
Class 12 Maths Board Syllabus CBSE 2018
Class 12 Maths Board Syllabus CBSE 2018Class 12 Maths Board Syllabus CBSE 2018
Class 12 Maths Board Syllabus CBSE 2018
 
Criminal Record System
Criminal Record SystemCriminal Record System
Criminal Record System
 
Infrared Security System
Infrared Security SystemInfrared Security System
Infrared Security System
 
The Preparation Of Potash Alum
The Preparation Of Potash AlumThe Preparation Of Potash Alum
The Preparation Of Potash Alum
 
Soil pollution
Soil pollutionSoil pollution
Soil pollution
 
Software concepts
Software conceptsSoftware concepts
Software concepts
 

Recently uploaded

社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .NABLAS株式会社
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单ewymefz
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundOppotus
 
Investigate & Recover / StarCompliance.io / Crypto_Crimes
Investigate & Recover / StarCompliance.io / Crypto_CrimesInvestigate & Recover / StarCompliance.io / Crypto_Crimes
Investigate & Recover / StarCompliance.io / Crypto_CrimesStarCompliance.io
 
Computer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sComputer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sMAQIB18
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单ewymefz
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单ukgaet
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单ocavb
 
Uber Ride Supply Demand Gap Analysis Report
Uber Ride Supply Demand Gap Analysis ReportUber Ride Supply Demand Gap Analysis Report
Uber Ride Supply Demand Gap Analysis ReportSatyamNeelmani2
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单vcaxypu
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhArpitMalhotra16
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP
 
How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?DOT TECH
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单yhkoc
 
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...elinavihriala
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单nscud
 
Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJames Polillo
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatheahmadsaood
 

Recently uploaded (20)

社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
Investigate & Recover / StarCompliance.io / Crypto_Crimes
Investigate & Recover / StarCompliance.io / Crypto_CrimesInvestigate & Recover / StarCompliance.io / Crypto_Crimes
Investigate & Recover / StarCompliance.io / Crypto_Crimes
 
Computer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sComputer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage s
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
 
Slip-and-fall Injuries: Top Workers' Comp Claims
Slip-and-fall Injuries: Top Workers' Comp ClaimsSlip-and-fall Injuries: Top Workers' Comp Claims
Slip-and-fall Injuries: Top Workers' Comp Claims
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单
 
Uber Ride Supply Demand Gap Analysis Report
Uber Ride Supply Demand Gap Analysis ReportUber Ride Supply Demand Gap Analysis Report
Uber Ride Supply Demand Gap Analysis Report
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...
2024-05-14 - Tableau User Group - TC24 Hot Topics - Tableau Pulse and Einstei...
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization Sample
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive data
 

OPTIMAL BINARY SEARCH

  • 1. Optimal Binary Search DESIGN ANALYSIS AND ALGORITHM CSE3004
  • 2. What is the problem? • Determining the cost and the structure of the Optimal Binary Search Tree (OBST) for a set of 4 keys to find the smallest possible search time for a given sequence of accesses. INDEX 0 11 2 3 NODE 43 13 80 74 FREQUENCY 3 4 8 9
  • 3. Algorithm • Here, the Optimal Binary Search Tree Algorithm is presented. • First, we build a BST from a set of provided n number of distinct keys < k1, k2, k3, ... kn >. • Here we assume, the probability of accessing a key Ki is pi. • Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be performed for the values which are not present in the Key set K. • We assume, for each dummy key di probability of access is qi.
  • 4. Algorithm int sum(int freq[], int i, int j); int optCost(int freq[], int i, int j) { if (j < i) // no elements in this subarray return 0; if (j == i) return freq[i]; int fsum = sum(freq, i, j); int min = INT_MAX; 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 min + fsum; } int optimalSearchTree(int keys[], int freq[], int n) { return optCost(freq, 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; }
  • 5. Solving the Problem • First for l = 1 calculating costs of following Cost[0,0] = 3 Cost[1,1] = 4 Cost[2,2] = 8 Cost[3,3] = 9 • Now for l = 2 calculating cost Cost[0,1] = 10 Cost[1,2] = 16
  • 6. Solving the Problem • For l = 2 calculating cost Cost[2,3] = 25 • Now for l = 3 calculating cost Cost[0,2] = 25 Cost[1,3] = 34 • For l = 4 calculating cost Cost[0,3] = 43 (Maximum frequency)
  • 7. Calculating Minimum Frequency From the matrix 43 is the maximum value with node (2) Now mention second node as a root node, with all the other nodes as the child nodes and the following optimal binary search tree is formed Checking frequency as per formed obst. Total frequency = 8x1 + 3x2 + 9x2 + 4x3 = 9 + 16 + 18 + 12 = 43 Hence Verified.