-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimalCostBST.cpp
More file actions
69 lines (54 loc) · 1.24 KB
/
Copy pathOptimalCostBST.cpp
File metadata and controls
69 lines (54 loc) · 1.24 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
using namespace std;
int arraySum(int i, int j, int cost[]) {
int sum = 0;
for (int start = i;start <= j;start++)
sum += cost[start];
return sum;
}
int optimalCostBST(int node[], int cost[], int n) {
int **m = new int*[n];
for (int i = 0;i < n;i++) {
m[i] = new int[n];
}
for (int i = 0;i < n;i++)
for (int j = 0;j < n;j++)
m[i][j] = 0;
for (int i = 0;i < n;i++)
{
m[i][i] = cost[i];
}
for (int l = 2;l <= n;l++) {
for (int i = 0 ; i <= n - l ; i++) {
int j = i + l - 1;
m[i][j] = INT_MAX;
//compute cost
for (int r = i;r <= j;r++) {
int sum = arraySum(i, j, cost) +
((r > i) ? m[i][r - 1] : 0) +
((r < j) ? m[r + 1][j] : 0);
if (sum < m[i][j])
m[i][j] = sum;
}
}
}
cout << "final computed dynamic matrix : \n\n";
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++)
cout << m[i][j] << " ";
cout << endl;
}
return m[0][n-1];
}
int main() {
int n;
cout << "Enter the number of nodes in the BST :" << endl;
cin >> n;
int *node = new int[n];
int *cost = new int[n];
cout << "Enter each node and their cost " << endl;
for (int i = 0;i < n;i++)
cin >> node[i] >> cost[i];
cout << "\n\nMin cost = " << optimalCostBST(node, cost, n);
return 0;
}