数列区间最大值

题目描述

思路

RMQ 问题 ST算法

代码

#include 
#include 
#define max(a, b) ((a) > (b) ? (a) : (b))
int n, m;
int arr[100005];
int f[100005][21], log[100005];
inline int read() {
    int s = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') ch = getchar();
    while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s;
}
int main() {
    n = read(), m = read(); 
    log[0] = -1;
    for (int i = 1; i <= n; ++i) {
        arr[i] = read();
        log[i] = log[i >> 1] + 1;
        f[i][0] = arr[i];
    }
    for (int i = 1; i <= 20; ++i) {
        for (int j = 1; j + (1 << i) - 1 <= n; ++j) {
            f[j][i] = max(f[j][i - 1], f[j + (1 << (i - 1))][i - 1]);
        } 
    }
    for (int i = 1, a, b, c; i <= m; ++i) {
        a = read(), b = read();
        c = log[b - a + 1];
        printf("%d\n", max(f[a][c], f[b - (1 << c) + 1][c]));
    }
    return 0;
}

转载于:https://www.cnblogs.com/liuzz-20180701/p/11490680.html

你可能感兴趣的:(数列区间最大值)