Skip to content

Commit 541a578

Browse files
committed
Optimal BST
1 parent 589811d commit 541a578

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

OptimalBST.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <bits/stdc++.h>
2+
#define N 10
3+
using namespace std;
4+
5+
int cost[N][N], obst[N][N], prefix[N];
6+
7+
void findOptimalBST(int keys[], int freq[], int n) {
8+
int i,j,l,r;
9+
/*precompute prefix sums*/
10+
prefix[0] = freq[0];
11+
for(i=1; i<n; i++) {
12+
prefix[i] = prefix[i-1] + freq[i];
13+
}
14+
15+
/*
16+
* If key[i] is the only node in the tree, cost will be the freq[i]*1
17+
* since key[i] will be the root(with depth = 0) and it'll be visited freq[i] times
18+
*/
19+
for(i=0; i<n; i++) {
20+
cost[i][i] = freq[i];
21+
obst[i][i] = i;
22+
}
23+
for(l=2; l<=n; l++) {
24+
for(i=0; i<=n-l+1; i++) {
25+
j = i+l-1;
26+
cost[i][j] = INT_MAX;
27+
/*Calculate cost for each element in [i,j] as the root and take the minimum*/
28+
for(r=i; r<=j; r++) {
29+
int c = ((r>i)?cost[i][r-1]:0) +
30+
((r<j)?cost[r+1][j]:0) +
31+
(prefix[j] - (i-1>=0?prefix[i-1]:0));
32+
if(c < cost[i][j]) {
33+
cost[i][j] = c;
34+
obst[i][j] = r;
35+
}
36+
}
37+
}
38+
}
39+
}
40+
41+
int main() {
42+
int i,n;
43+
cin>>n; //number of nodes in the tree
44+
int keys[n], freq[n];
45+
for(i=0; i<n; i++) {
46+
cin>>keys[i]>>freq[i];
47+
}
48+
findOptimalBST(keys, freq, n);
49+
cout<<"Optimal cost = "<<cost[0][n-1]<<endl;
50+
return 0;
51+
}

0 commit comments

Comments
 (0)