poj3264 ST算法模板题
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 80000;
const int maxm = 30;
int d_min[maxn][maxm],d_max[maxn][maxm],a[maxn];
int n;
void RMQ_init(){
int i,j;
for(i = 1; i <= n; i++){
d_min[i][0] = a[i];
d_max[i][0] = a[i];
}
for(j = 1; (1<<j) <= n; j++)
for(i = 1; i + j - 1 <= n; i++){
d_min[i][j] = min(d_min[i][j-1],d_min[i + (1<<(j-1))][j-1]);
d_max[i][j] = max(d_max[i][j-1],d_max[i + (1<<(j-1))][j-1]);
}
}
int RMQ_min(int l,int r){
int k = 0;
while((1<<(k+1)) <= r-l+1)
k++;
return min(d_min[l][k], d_min[r-(1<<k)+1][k]);
}
int RMQ_max(int l,int r){
int k = 0;
while((1<<(k+1)) <= r-l+1)
k++;
return max(d_max[l][k], d_max[r-(1<<k)+1][k]);
}
int main()
{
int q,l,r,i;
scanf("%d%d",&n,&q);
for(i = 1; i <= n; i++)
scanf("%d",&a[i]);
RMQ_init();
while(q--){
scanf("%d%d",&l,&r);
printf("%d
",RMQ_max(l,r)-RMQ_min(l,r));
}
return 0;
}