VJ Balanced Lineup(ST表)
原题
一道很裸的RMQ,线段树专题里刷的,直接打ST表就好。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll f1[50005][20],f2[50005][20],a[50005];//二维数组别开太大,不然MLE了
int n,q,l,r;
void ST_prework()
{
for(int i=1; i<=n; i++)
{
f1[i][0]=f2[i][0]=a[i];
}
for(int j=1; (1<<j)<=n; j++)
for(int i=1; i+(1<<j)-1<=n; i++)
{
f1[i][j]=max(f1[i][j-1],f1[i+(1<<(j-1))][j-1]);
f2[i][j]=min(f2[i][j-1],f2[i+(1<<(j-1))][j-1]);
}
}
ll ST_querymax(int l,int r)
{
int k=log(r-l+1)/log(2);
return max(f1[l][k],f1[r-(1<<k)+1][k]);
}
ll ST_querymin(int l,int r)
{
int k=log(r-l+1)/log(2);
return min(f2[l][k],f2[r-(1<<k)+1][k]);
}
int main()
{
cin>>n>>q;
for(int i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
}
ST_prework();
while(q--)
{
ll x,y;
scanf("%d%d",&l,&r);
x=ST_querymax(l,r);
y=ST_querymin(l,r);
printf("%lld\n",x-y);
}
return 0;
}
戒骄戒躁,百炼成钢!