RMQ模板
题目链接
http://poj.org/problem?id=3264
详解看这里
http://www.cnblogs.com/Missa/archive/2012/10/01/2709686.html
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
#define maxn 1000000+5
#define N 20
int f[N][N];
int data[maxn];
int ma[maxn][N];
int mi[maxn][N];
int n , m ;
void init()
{
for(int j = 1 ; j <= N ; ++j)
{
for(int i = 1 ; i <= n ; ++i )
{
if(i+(1<<j)-1 <= n){
ma[i][j] = max(ma[i][j-1] , ma[i+(1 << (j-1))][j-1]);
mi[i][j] = min(mi[i][j-1] , mi[i+(1 << (j-1))][j-1]);
}
}
}
}
int main()
{
while(cin >> n >> m)
{
for(int i = 1 ; i <= n ; ++i)
{
scanf("%d",&data[i]);
mi[i][0] = data[i];
ma[i][0] = data[i];
}
init();
while( m-- )
{
int a,b,k = 0 ;
scanf("%d %d",&a,&b);
int len = b - a + 1;
while ( (1 << k ) <= len )k++;
k--;
//k = log(b-a+1)/log(2.0);
int x = max( ma[a][k] , ma[b-(1<<k)+1][k] );
int y = min( mi[a][k] , mi[b-(1<<k)+1][k] );
// printf("x = %d y = %d\n",x,y);
cout << x - y << endl;
}
}
}