思路:熟悉RMQ的题目,求区间最大值减去最小值
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 50000+100;
int dmax[maxn][20];
int dmin[maxn][20];
int d[maxn];
void initmax(int n,int d[])
{
for (int i = 1;i<=n;i++)
dmax[i][0]=d[i];
for (int j = 1;(1<<j)<=n;j++)
for (int i = 1;i+(1<<j)-1<=n;i++)
dmax[i][j]=max(dmax[i][j-1],dmax[i+(1<<(j-1))][j-1]);
}
int getmax(int L,int R)
{
int k = 0;
while ((1<<(k+1)) <= R-L+1)
k++;
return max(dmax[L][k],dmax[R-(1<<k)+1][k]);
}
void initmin(int n,int d[])
{
for (int i = 1;i<=n;i++)
dmin[i][0]=d[i];
for (int j = 1;(1<<j)<=n;j++)
for (int i = 1;i+(1<<j)-1<=n;i++)
dmin[i][j]=min(dmin[i][j-1],dmin[i+(1<<(j-1))][j-1]);
}
int getmin(int L,int R)
{
int k = 0;
while ((1<<(k+1)) <= R-L+1)
k++;
return min(dmin[L][k],dmin[R-(1<<k)+1][k]);
}
int main()
{
int n,q;
while (scanf("%d%d",&n,&q)!=EOF)
{
for (int i = 1;i<=n;i++)
scanf("%d",&d[i]);
initmax(n,d);
initmin(n,d);
while (q--)
{
int L,R;
scanf("%d%d",&L,&R);
printf("%d\n",getmax(L,R)-getmin(L,R));
}
}
}