This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Segement_Tree_RMQ.cpp
64 lines (47 loc) · 1.52 KB
/
Segement_Tree_RMQ.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
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
int RMQ(int segArray[], int segStart, int segEnd, int start, int end, int index)
{
if (start <= segStart && end >= segEnd)
return segArray[index];
if (segEnd < start || segStart > end)
return INT_MAX;
int mid = segStart + (segEnd - segStart) / 2;
int left = RMQ(segArray, segStart, mid, start, end, 2*index + 1);
int right = RMQ(segArray, mid + 1, segEnd, start, end, 2*index + 2);
return (left <= right ? left : right);
}
int buildSegmentTree(int array[], int start, int end, int segArray[], int index)
{
if (start == end)
{
segArray[index] = array[start];
return array[start];
}
int mid = start + (end - start) / 2;
int left = buildSegmentTree(array, start, mid, segArray, index*2 + 1);
int right = buildSegmentTree(array, mid + 1, end, segArray, index*2 + 2);
segArray[index] = (left <= right ? left : right);
return segArray[index];
}
int main()
{
int array[10] = {1, 3, 2, 7, 9, 11, 8, 4, 20, 15};
int size = 10;
int height = ceil( log2(size) );
int segtree_size = 2 * (pow(2, height) - 1);
int *segArray = new int[segtree_size];
buildSegmentTree(array, 0, size - 1, segArray, 0);
int start = 1, end = 5;
cout << "Minimum value in index range " << start << " to " << end << " is" << endl;
cout << RMQ(segArray, 0, size - 1, start, end, 0) << endl;
return 0;
}
/* Output
*
* Minimum value in index range 1 to 5 is
* 2
*
*/