RMQ

优化可以存log2(N),pow(2,n)可以用<< 来实现

#include 
#include 
#include 
#include
#include
using namespace std;
const int N = 50005;
const int Q = 200005;
int str[N];
int f[N][16];
int ff[N][16];
int n, q;
int MAX(int a, int b)
{
    if (a > b)
    return a;
    return b;
}
int MIN(int a, int b)
{
    if (a < b)
        return a;
    return b;
}
int fun1(int a, int b)
{
    int nn = b - a + 1;
    int c;
    int mm = str[a];
    while (nn!=0)
    {
        c = log2(nn);//2的指数;
        nn = nn - (int)pow(2, c);//剩下的数;
        if (mm < f[a][c])
        {
            mm = f[a][c];
        }
        a = a + (int)pow(2, c);
    }
    return mm;
}
int fun2(int a, int b)
{
    int nn = b - a + 1;
    int c;
    int mm = str[a];
    while (nn != 0)
    {
        c = log2(nn);//2的指数;
        nn = nn - (int)pow(2, c);//剩下的数;
        if (mm > ff[a][c])
        {
            mm = ff[a][c];
        }
        a = a + (int)pow(2, c);
    }
    return mm;
}
int main()
{
    scanf("%d%d", &n, &q);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &str[i]);
        f[i][0] = str[i];
        ff[i][0] = str[i];
    }
        for (int j = 1; j <= log2(n); j++)
        {
            for (int i = 1; i <= n, (int)pow(2, j) + i - 1 <= n; i++)
            {
                f[i][j] = MAX(f[i][j - 1], f[i + (int)pow(2, j - 1)][j - 1]);//预处理最大值
                ff[i][j] = MIN(ff[i][j - 1], ff[i + (int)pow(2, j - 1)][j - 1]);//预处理最小值
            }
        }
        int a, b;
        for (int i = 1; i <= q; i++)
        {
            scanf("%d%d", &a, &b);
            printf("%d\n", fun1(a, b) - fun2(a, b));
        }
    return 0;
}

你可能感兴趣的:(RMQ)