题目链接poj3264
线段树
- 细心
- 存两个信息。。。
#include<cstdio>
#include<algorithm>
using namespace std;
struct aa{
int l,r;
int maxx,minx;
}b[200005*4];
int a[2000005];
int n,q;
void build(int p,int l,int r){
b[p].l=l;
b[p].r=r;
if(l==r){
b[p].maxx =b[p].minx= a[l];
return;
}
int mid = (l+r)>>1;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
b[p].maxx = max(b[p*2].maxx,b[p*2+1].maxx);
b[p].minx = min(b[p*2].minx,b[p*2+1].minx);
}
int ask(int p,int l,int r,bool flag){
if(b[p].l == l&&b[p].r == r)
{
if(flag)
return b[p].maxx;
else
return b[p].minx;
}
int mid=(b[p].l+b[p].r)>>1;
if(r<=mid)
ask(p*2,l,r,flag);
else if(l>mid)
ask(p*2+1,l,r,flag);
else
{
if(flag)
return max(ask(p*2+1,mid+1,r,flag),ask(p*2,l,mid,flag));
else
return min(ask(p*2+1,mid+1,r,flag),ask(p*2,l,mid,flag));
}
}
int main(){
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
build(1,1,n);
for(int i =1;i<=q;i++){
int aa,bb;
scanf("%d%d",&aa,&bb);
printf("%d\n",ask(1,aa,bb,true)-ask(1,aa,bb,false));
}
return 0;
}
ST表
由luogu3865得到
#include<bits/stdc++.h>
using namespace std;
const int logn = 21;
const int maxn=2000001;
int f[maxn][logn],Logn[maxn],m,n;
void pre(){
Logn[1] = 0;
Logn[2] = 1;
for(int i = 3;i<maxn;i++){
Logn[i] = Logn[i/2]+1;
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&f[i][0]);
}
pre();
for(int j = 1;j<=logn;j++)
for(int i =1;i+(1<<j)-1<=n;i++){
f[i][j] = max(f[i][j-1],f[i+(1<<j-1)][j-1]);
}
for(int i =1;i<=m;i++){
int x,y;
scanf("%d%d",&x,&y);
int s = Logn[y-x+1];
printf("%d\n",max(f[x][s],f[y-(1<<s)+1][s]));
}
return 0;
}
ST表的模版题目转化一下
把记录最值的数组换成最大最小值数组
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 50005;
const int Logn = 16;
int fmax[maxn][Logn],fmin[maxn][Logn],logn[maxn],n,m;
void pre(){
logn[1]=0;
logn[2]=1;
for(int i=3;i<=maxn;i++)
logn[i] = logn[i/2]+1;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
fmin[i][0]=x;
fmax[i][0]=x;
}
pre();
for(int j =1;j<=Logn;j++){
for(int i=1;i+(1<<j)-1<=n;i++){
fmin[i][j]=min(fmin[i][j-1],fmin[i+(1<<(j-1))][j-1]);
fmax[i][j]=max(fmax[i][j-1],fmax[i+(1<<(j-1))][j-1]);
}
}
for(int i=1;i<=m;i++){
int l,r;
scanf("%d%d",&l,&r);
int s = logn[r-l+1];
printf("%d\n",max(fmax[l][s],fmax[r-(1<<s)+1][s])-min(fmin[l][s],fmin[r-(1<<s)+1][s]));
}
return 0;
}
得到最终结果也能过,时间会更短一些