-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathOptimum Binary Search Tree.cpp
More file actions
30 lines (25 loc) · 946 Bytes
/
Optimum Binary Search Tree.cpp
File metadata and controls
30 lines (25 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<bits/stdc++.h>
using namespace std;
int frequency[100] = {0}; // frequencies of the elements
int weight[100] = {0}; // weights of the elements; weight[i] = sum(weight[0] -> weight[i-1])
int memo[100][100];
int BST(int start, int end) // optimum BST for range
{
if (end < start) return 0; // out of range
if (start >= end) return 0;
if (memo[start][end] != -1) return memo[start][end];
int curCost, minCost = INT_MAX;
for (int i=start; i<=end; i++) // minimum value considering each element as root
{
curCost = BST(start, i - 1) + BST(i + 1, end) + weight[end] - weight[start-1] - frequency[i]; // cost if i is root
if (curCost < minCost)
{
minCost = curCost;
memo[start][end] = minCost;
}
}
return memo[start][end];
}
int main()
{
}