Pagini recente » Cod sursa (job #136907) | Cod sursa (job #1443530) | Cod sursa (job #2290821) | Cod sursa (job #1956988) | Cod sursa (job #2969739)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
struct nod{
int value,left_bound,right_bound;
nod *left_child,*right_child;
};
int n,ar[1000005],m;
nod* create_nod(int *v,int left_bound,int right_bound)
{
nod *q=new nod;
q->left_bound=left_bound;
q->right_bound=right_bound;
if(right_bound==left_bound)
{
q->value=ar[left_bound];
q->left_child=NULL;
q->right_child=NULL;
return q;
}
int mij=(left_bound+right_bound)/2;
q->left_child=create_nod(v,left_bound,mij);
q->right_child=create_nod(v,mij+1,right_bound);
q->value=min(q->left_child->value,q->right_child->value);
return q;
}
void free_nod(nod *r)
{
if(r==NULL)
return;
free_nod(r->left_child);
free_nod(r->right_child);
delete r;
}
int query(nod *r,int a, int b)
{
if(r->right_bound<a || r->left_bound>b)
return INT_MAX;
if(r->left_bound>=a && r->right_bound<=b)
return r->value;
int s1 = query(r->left_child,a,b);
int s2 = query(r->right_child,a,b);
return min(s1,s2);
}
int main()
{
fin>>n>>m;
for(int i=1;i<=n;i++)
fin>>ar[i];
int x,y;
nod *q=create_nod(ar,1,n);
for(int i=1;i<=m;i++)
{
fin>>x>>y;
fout<<query(q,x,y)<<"\n";
}
free_nod(q);
return 0;
}