题目
https://www.luogu.com.cn/problem/P5097
思路
简单的静态区间最值,开一个ST表就可以搞定(更熟悉线段树的同学比如我可以用线段树写),但ST表码量更小且常数小。
ST表利用了倍增的思想,就是维护以i位置开头的,长度为(2^k)的区间段中的最值,记为ST[i][k],易得,ST[i][k]=min(ST[i][k-1],ST[i+(2^{k-1})][k-1])。
查询l,r的区间最小值,就是找到一个最大的k,使(2^kleq) r-l+1。
然后
可能会重叠,但是不要紧,重叠不影响最值。
由于太久没写,我代码里的ST[i][k]指的是以[i]结尾的区间信息QwQ。可能会麻烦一点。
代码
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#define maxn 30000
using namespace std;
int a[maxn],st[maxn][16];
int log_2[maxn];
int main(){
int n,q,i,j,x,y,ans;
scanf("%d%d",&n,&q);
for(i=2;i<=n;++i)
log_2[i]=log_2[i>>1]+1;
for(i=1;i<=n;++i)
scanf("%d",&st[i][0]);
for(j=1;j<=log_2[n];j++){
for(i=1;i<=n;++i){
if(i>=(1<<j-1)) st[i][j]=min(st[i][j-1],st[i-(1<<j-1)][j-1]);
}
}
for(i=1;i<=q;++i){
scanf("%d%d",&x,&y);
int k=log_2[y-x+1];
ans=min(st[y][k],st[x-1+(1<<k)][k]);
printf("%d
",ans);
}
// system("pause");
return 0;
}