-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prac8-D18.cpp
109 lines (96 loc) · 2.3 KB
/
Prac8-D18.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*Given sequence k = k1 <k2 < … <kn of n sorted keys, with a search probability pi for each
key ki . Build the Binary search tree that has the least search cost given the access
probability for each key? */
#include <iostream>
#include <limits.h>
using namespace std;
struct Node
{
int key;
Node *left, *right;
Node(int k)
{
key = k;
left = NULL;
right = NULL;
}
};
// function to find optimal root
int findOptimalRoot(int keys[], int freq[], int start, int end)
{
int sum = 0;
for (int i = start; i <= end; i++)
{
sum += freq[i];
}
int minCost = INT_MAX;
int cost;
for (int i = start; i <= end; i++)
{
cost = sum + ((i > start) ? findOptimalRoot(keys, freq, start, i - 1) : 0) + ((i < end) ? findOptimalRoot(keys, freq, i + 1, end) : 0);
if (cost < minCost)
{
minCost = cost;
}
}
return minCost;
}
// function to construct and optimal bst
Node *buildOptimalBST(int keys[], int freq[], int start, int end)
{
if (start > end)
{
return NULL;
}
int minIdx;
int minCost = INT_MAX;
int cost;
for (int i = start; i <= end; i++)
{
cost = findOptimalRoot(keys, freq, start, end);
if (cost < minCost)
{
minCost = cost;
minIdx = i;
}
}
Node *root = new Node(keys[minIdx]);
root->left = buildOptimalBST(keys, freq, start, minIdx - 1);
root->right = buildOptimalBST(keys, freq, minIdx + 1, end);
return root;
}
void inorder(Node *root)
{
if (root == NULL)
{
return;
}
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
int main()
{
cout<<"DSAL Practical No. 08 (D-18)"<<endl;
cout<<"Prepared By : Anshul Singh"<<endl;
int k;
cout << "\nEnter number of keys: ";
cin >> k;
cout << "\nEnter keys: ";
int keys[k];
for (int i = 0; i < k; i++)
{
cin >> keys[i];
}
cout << "\nEnter the frequencies of keys: ";
int freq[k];
for (int i = 0; i < k; i++)
{
cin >> freq[i];
}
int n = sizeof(keys) / sizeof(keys[0]);
Node *root = buildOptimalBST(keys, freq, 0, n - 1);
cout << "\n Inorder traversal of the optimal binary search tree: ";
inorder(root);
return 0;
}