RMQ区间最大值与最小值查询

时间:2020-12-25 15:15:47

 RMQ复杂度:建表$O\left ( nlgn \right ) $,查询$O\left ( 1 \right )$

 

ll F_Min[maxn][20],F_Max[maxn][20];

void Init()
{
    for(int i = 1; i <= n; i++)
    {
        F_Min[i][0] = F_Max[i][0] = num[i];
    }

    for(int i = 1; (1<<i) <= n; i++)  //按区间长度递增顺序递推
    {
        for(int j = 1; j+(1<<i)-1 <= n; j++)  //区间起点
        {
            F_Max[j][i] = max(F_Max[j][i-1],F_Max[j+(1<<(i-1))][i-1]);
            F_Min[j][i] = min(F_Min[j][i-1],F_Min[j+(1<<(i-1))][i-1]);
        }
    }
}

ll Query_max(int l,int r)//l到r,num数组的最大值
{
    int k = (int)(log(double(r-l+1))/log((double)2));
    return max(F_Max[l][k], F_Max[r-(1<<k)+1][k]);
}

ll Query_min(int l,int r)//l到r,num数组的最小值
{
    int k = (int)(log(double(r-l+1))/log((double)2));
    return min(F_Min[l][k], F_Min[r-(1<<k)+1][k]);
}