Created
August 18, 2018 06:55
-
-
Save gatij/035276170724aeac8587057513224b87 to your computer and use it in GitHub Desktop.
Range Minimum Query Segment Tree c++ implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
class SegmentTree{ | |
long long n; | |
vector<long long>A,st; | |
long long left(long long p) | |
{ | |
return (p<<1); | |
} | |
long long right(long long p) | |
{ | |
return (p<<1)+1; | |
} | |
void build(long long p,long long l,long long r) | |
{ | |
if(l==r) | |
st[p]=l; | |
else | |
{ | |
build(left(p),l,(l+r)/2); | |
build(right(p),((l+r)/2)+1,r); | |
long long li=st[left(p)]; | |
long long ri=st[right(p)]; | |
if(A[li]<A[ri]) | |
st[p]=li; | |
else | |
st[p]=ri; | |
} | |
} | |
long long rmq(long long p,long long l,long long r,long long i,long long j) | |
{ | |
if(i>r || j<l) | |
return -1; | |
else if(l>=i && r<=j) | |
return st[p]; | |
long long li=rmq(left(p),l,(l+r)/2,i,j); | |
long long ri=rmq(right(p),((l+r)/2)+1,r,i,j); | |
if(li==-1) | |
return ri; | |
else if(ri==-1) | |
return li; | |
else | |
{ | |
if(A[li]<A[ri]) | |
return li; | |
else | |
return ri; | |
} | |
} | |
public: | |
SegmentTree(const vector<long long> &_A) | |
{ | |
A=_A; | |
n=(long long)(A.size()); | |
st.assign(4*n,0); | |
build(1,0,n-1); | |
} | |
long long rmq(long long i,long long j) | |
{ | |
return rmq(1,0,n-1,i,j); | |
} | |
}; | |
int main() | |
{ | |
long long a[]={2,1,7,5,4,6,4,3,5,4,9}; | |
vector<long long>v(a,a+11); | |
SegmentTree st(v); | |
cout<<"Range Minimun Query[L,R]=[1,8](index):"<<st.rmq(0,7)<<" value of min:"<<a[st.rmq(0,7)]<<"\n"; | |
cout<<"Range Minimun Query[L,R]=[9,11](index):"<<st.rmq(8,10)<<" value of min:"<<a[st.rmq(8,10)]<<"\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment