http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1174
给出一个有N个数的序列,编号0 - N - 1。进行Q次查询,查询编号i至j的所有数中,最大的数是多少。
例如: 1 7 6 3 1。i = 1, j = 3,对应的数为7 6 3,最大的数为7。(该问题也被称为RMQ问题)
Input
第1行:1个数N,表示序列的长度。(2 <= N <= 10000)
第2 - N + 1行:每行1个数,对应序列中的元素。(0 <= S[i] <= 10^9)
第N + 2行:1个数Q,表示查询的数量。(2 <= Q <= 10000)
第N + 3 - N + Q + 2行:每行2个数,对应查询的起始编号i和结束编号j。(0 <= i <= j <= N - 1)
Output
共Q行,对应每一个查询区间的最大值。
Input示例
5
1
7
6
3
1
3
0 1
1 3
3 4
Output示例
7
7
3
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
#define max(b,c) b>c?b:c
#define maxn 10010
int num;
int a[maxn];
struct point
{
int l;
int r;
int mav;
}node[maxn<<2];
void builtree(int L,int R,int P)
{
node[P].r=R;
node[P].l=L;
if(L==R)//叶子节点
{
node[P].mav=a[L];
return ;
}
int mid=(L+R)>>1;
builtree(L,mid,P<<1);//左孩子
builtree(mid+1,R,P<<1|1);//右孩子
node[P].mav=max(node[P<<1].mav,node[P<<1|1].mav);
}
int query(int L,int R,int P)
{
if(L<=node[P].l&&R>=node[P].r)
{
return node[P].mav;
}
int mid=(node[P].r+node[P].l)>>1;
int m_l=0,m_r=0;
if(L<=mid)
m_l=query(L,R,P<<1);
if(R>mid)
m_r=query(L,R,P<<1|1);
return max(m_l,m_r);
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
builtree(1,n,1);
int m;
cin>>m;
int x,y;
int ans;
while(m--)
{
cin>>x>>y;
ans=query(x+1,y+1,1);
cout<<ans<<endl;
}
return 0;
}