【luogu P2880 [USACO07JAN]平衡的阵容Balanced Lineup】 题解

题目链接:https://www.luogu.org/problemnew/show/P2880
是你逼我用ST表的啊qaq

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 500001;
int minst[maxn][21], maxst[maxn][21], a[maxn], l, r, n, m;
int main()
{
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&a[i]);
        minst[i][0] = a[i];
        maxst[i][0] = a[i];
    }
    for(int j = 1; (1<<j) <= n; j++)
    for(int i = 1; i <= n - (1<<j) + 1; i++)    
    {
        maxst[i][j] = max(maxst[i][j-1],maxst[i+(1<<(j-1))][j-1]);
        minst[i][j] = min(minst[i][j-1],minst[i+(1<<(j-1))][j-1]);
    }
    for(int i = 1; i <= m; i++)
    {
        scanf("%d%d",&l,&r);
        int j = 0;
        while((1<<(j+1)) <= (r - l + 1)) j++;
        printf("%d\n",max(maxst[l][j],maxst[r-(1<<j)+1][j])-min(minst[l][j],minst[r-(1<<j)+1][j]));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/MisakaAzusa/p/9275561.html