poj 3264(ST表)

poj 3264

ST表模板题。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ms(i, j) memset(i, j, sizeof i)
using namespace std;

const int MAXN = 50000 + 5;

int n, q;
int h[MAXN], fmaxi[MAXN][25], fmini[MAXN][25];
//h为原数组,fmaxi[i][j]为从i开始长度为2^j的区间最小值 

void initRMQ() {
    for (int i=1;i<=n;i++) fmaxi[i][0] = fmini[i][0] = h[i];//初始值为原数组 
    for (int j=1;(1<<j)<=n;j++) {//j必定在外层 
        for (int i=1;i+(1<<j)-1<=n;i++) {
            fmaxi[i][j] = max(fmaxi[i][j-1], fmaxi[i+(1<<(j-1))][j-1]);
            fmini[i][j] = min(fmini[i][j-1], fmini[i+(1<<(j-1))][j-1]);//DP
        }
    }
}
int RMQMax(int x, int y) {
    int k = (int)(log(y-x+1.0)/log(2.0));
    return max(fmaxi[x][k], fmaxi[y-(1<<k)+1][k]);
}
int RMQMin(int x, int y) {
    int k = (int)(log(y-x+1.0)/log(2.0));
    return min(fmini[x][k], fmini[y-(1<<k)+1][k]);
}
void clear() {}
void init() {
    clear();
    for (int i=1;i<=n;i++) scanf("%d", &h[i]);
    initRMQ();
}
void solve() {
    for (int i=1;i<=q;i++) {
        int a, b;
        scanf("%d%d", &a, &b);
        printf("%d\n", RMQMax(a, b) - RMQMin(a, b));
    }
}
int main() {
    #ifndef ONLINE_JUDGE
    freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
    #endif
    while (scanf("%d%d", &n, &q)==2&&n&&q) init(), solve();
    return 0;
}
------ 本文结束 ------