poj3264 Balanced Lineup *

/*
* 入门题
* RMQ Sparse-Table : O(nlgn) - O(1)
*
* 2000ms...
*
*/

#include <cstdio>
using namespace std;

const int maxN = 50000 + 10;
const int maxK = 50;

int height[maxN], n, q;
//记录的是坐标
int dMax[maxN][maxK], dMin[maxN][maxK];

inline int max(int lhs, int rhs){
return (height[lhs] > height[rhs] ? lhs : rhs);
}
inline int min(int lhs, int rhs){
return (height[lhs] < height[rhs] ? lhs : rhs);
}

void preST(){
for(int i=0; i<n; i++)
dMax[i][0] = dMin[i][0] = i;

for(int j=1; 1 << j <= n; j++){
for(int i=0; i + (1<<j) - 1 < n; i++){
dMax[i][j] = max(dMax[i][j-1], dMax[i+(1<<(j-1))][j-1]);
dMin[i][j] = min(dMin[i][j-1], dMin[i+(1<<(j-1))][j-1]);
}
}
}

//返货[x, y]的最大或最小值
int SparseTable(int x, int y, bool isMax){
//if(x == y) return height[x];
x--, y--;

int pow;
for(pow=1; 1 << pow < (y-x+1); pow++);
pow--;

if(isMax)
return height[max(dMax[x][pow], dMax[y-(1<<pow)+1][pow])];
else
return height[min(dMin[x][pow], dMin[y-(1<<pow)+1][pow])];

}


int main(){
scanf("%d %d", &n, &q);
for(int i=0; i<n; i++)
scanf("%d", &height[i]);

//预处理
preST();

int x, y;
for(int i=0; i<q; i++){
scanf("%d %d", &x, &y);

printf("%d\n", SparseTable(x, y, 1) - SparseTable(x, y, 0));
}





return 0;
}
原文地址:https://www.cnblogs.com/longdouhzt/p/2212681.html