题目链接:
https://vjudge.net/contest/309985#problem/H
这道题用rmq写的。看到还有线段树写法。有空来研究一下
线段树写法
https://www.cnblogs.com/blvt/p/7325968.html
rmq
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define inf (-((LL)1<<40))
#define lson k<<1, L, (L + R)>>1
#define rson k<<1|1, ((L + R)>>1) + 1, R
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define mem(a, b) memset(a, b, sizeof(a))
#define FIN freopen("in.txt", "r", stdin)
#define FOUT freopen("out.txt", "w", stdout)
#define rep(i, a, b) for(int i = a; i <= b; i ++)
#define dec(i, a, b) for(int i = a; i >= b; i --)
#define rmq_log2(x,val) while((1<<(x+1))<=val)x++;
template<class T> T MAX(T a, T b) { return a > b ? a : b; }
template<class T> T MIN(T a, T b) { return a < b ? a : b; }
template<class T> T GCD(T a, T b) { return b ? GCD(b, a%b) : a; }
template<class T> T LCM(T a, T b) { return a / GCD(a,b) * b; }
typedef long long LL;
const int maxn =50000+5;
const int MAXM = 110000;
const double eps = 1e-8;
LL MOD = 1000000007;
int n;
int a[maxn],dp1[maxn][20],dp2[maxn][20];
void rmq_init()
{
for(int i=1;i<=n;i++)
dp1[i][0]=dp2[i][0]=a[i];//初始化
for(int j=1;(1<<j)<=n;j++)
for(int i=1;i+(1<<j)-1<=n;i++)
{dp1[i][j]=max(dp1[i][j-1],dp1[i+(1<<(j-1))][j-1]);
dp2[i][j]=min(dp2[i][j-1],dp2[i+(1<<(j-1))][j-1]);}
}
int rmq(int l,int r)
{
int k=0;
rmq_log2(k,r-l+1)
return max(dp1[l][k],dp1[r-(1<<k)+1][k])-min(dp2[l][k],dp2[r-(1<<k)+1][k]);
}
int main()
{
int k;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
rmq_init();
int x,y;
while(k--){
scanf("%d%d",&x,&y);
printf("%d\n",rmq(x,y));
}
}