题意:求区间上最大值和最小值的差,RMQ模板题,下面是用ST算法来解
代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>
#define inf 0x7fffffff
#define eps 1e-9
#define pi acos(-1.0)
#define N 50005
#define P system("pause")
using namespace std;
int a[N],d1[N][20],d2[N][20];
int n,m;
int res1,res2;
void RMQ_init()
{
int i,j;
for(i = 0; i < n; i++)
d1[i][0] = d2[i][0] = a[i];
for(j = 1; (1<<j) <= n; j++)
for(i = 0; i+(1<<j)-1 < n; i++)
{
d1[i][j] = min(d1[i][j-1], d1[i+(1<<(j-1))][j-1]);
d2[i][j] = max(d2[i][j-1], d2[i+(1<<(j-1))][j-1]);
}
}
void RMQ(int l,int r)
{
int k = 0;
while((1<<(k+1)) <= r-l+1) k++;
res1 = min(d1[l][k], d1[r-(1<<k)+1][k]);
res2 = max(d2[l][k], d2[r-(1<<k)+1][k]);
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
scanf("%d%d",&n,&m);
int i,j;
for(i = 0; i < n; i++)
scanf("%d",&a[i]);
RMQ_init();
while(m--)
{
int r,l;
scanf("%d%d",&l,&r);
RMQ(l-1,r-1);
printf("%d\n",res2 - res1);
}
return 0;
}