Description
每天,农夫 John 的N(1 <= N <= 50,000)头牛总是按同一序列排队. 有一天, John 决定让一些牛们玩一场飞盘比赛. 他准备找一群在对列中为置连续的牛来进行比赛. 但是为了避免水平悬殊,牛的身高不应该相差太大. John 准备了Q (1 <= Q <= 180,000) 个可能的牛的选择和所有牛的身高 (1 <= 身高 <= 1,000,000). 他想知道每一组里面最高和最低的牛的身高差别. 注意: 在最大数据上, 输入和输出将占用大部分运行时间.
Input
第一行: N 和 Q. * 第2..N+1行: 第i+1行是第i头牛的身高.
第N+2..N+Q+1行: 两个整数, A 和 B (1 <= A <= B <= N), 表示从A到B的所有牛.
Output
*第1..Q行: 所有询问的回答 (最高和最低的牛的身高差), 每行一个.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
solution: ST表
/**************************************************************
Problem: 1699
User: Venishel
Language: C++
Result: Accepted
Time:984 ms
Memory:41132 kb
****************************************************************/#include <cstdio>
#include <iostream>
using namespace std;#define N 200007int a[N], dx[N][25], dn[N][25];
int n;void RMQ_init(){
for ( int i = 1; i <= n; i++) dx[i][0] = dn[i][0] = a[i];
for ( int j = 1; (1<<j) <= n; j++)
for ( int i = 1; i + ( 1<< j ) -1 <= n; i++){
dx[i][j] = max( dx[i][j-1], dx[i+(1<<(j-1))][j-1] );
dn[i][j] = min( dn[i][j-1], dn[i+(1<<(j-1))][j-1] );
}
}int RMQ( int L, int R ){
int k = 0;
while ( 1<<(k+1) <= R-L+1 ) k++;
return max( dx[L][k], dx[R-(1<<k)+1][k]) - min( dn[L][k], dn[R-(1<<k)+1][k]);
}
/*
void RMQ_init(){
for ( int i = 1; i <= n; i++ ) d[i][0] = a[i];
for ( int j = 1; (1<<j) <= n; j++ )
for ( int i = 1; i +( 1<<j )-1 <= n; i++)
d[i][j] = max( d[i][j-1], d[ i + (1<<(j-1))][j-1]);
}int RMQ( int L, int R ){
int k = 0;
while ( (1<<(k+1)) <= R-L+1 ) k++;
return max( d[L][k], d[R-(1<<k)+1][k]);
}
*/
int main(){
int q;
scanf( "%d%d", &n, &q);
for ( int i = 1; i <= n; i++ ) scanf( "%d", &a[i] );
RMQ_init();
for ( int i = 1; i <= q; i++){
int x, y;
scanf( "%d%d", &x, &y );
printf( "%d\n", RMQ(x, y));
}
return 0;
}