bzoj 4491. 我也不知道题目名字是什么 题解

Preface

题目链接

Description

给定一个序列A[i],每次询问l,r,求[l,r]内最长子串,使得该子串为不上升子串或不下降子串

N,Q<=50000

Solution

设 $L[i]$ 表示以 $i$ 为起点,往左最多能成为子串的长度,$R[i]$ 表示以 $i$ 为起点,往右最多能成为子串的长度。

那么很显然区间 $[l,r]$ 答案就是 $\max\{R[l],R[l+1],\dots,R[r-L[r]],L[r]\}$(处理边界)

那么再套一个线段树就好了

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define W while
#define I inline
#define RI register int
#define LL long long
#define Cn const
#define gc getchar
#define D isdigit(c=gc())
#define pc(c) putchar((c))
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
using namespace std;
class FileInput{
private:
#define FS 100000
#define tc() (A==B&&(B=(A=FI)+fread(FI,1,FS,stdin),A==B)?EOF:*A++)
int f;char c,*A,*B,FI[FS];
public:
I FileInput(){A=B=FI;}
Tp I void read(Ty& x){x=0,f=1;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;}
Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'));}
}F;
Cn int N=50010;
int n,a[N],q,l,r,L[N],R[N],T[N],tr[N];
I void build(int x,int l,int r){
if(l==r) return void(tr[x]=R[l]);
int mid=l+r>>1;
build(x<<1,l,mid),build(x<<11,mid+1,r);
tr[x]=max(tr[x<<1],tr[x<<11]);
}
I int query(int x,int l,int r,int L,int R){
if(L<=l&&r<=R) return tr[x];
int mid=l+r>>1,res=0;
if(L<=mid) res=max(res,query(x<<1,l,mid,L,R));
if(R>mid) res=max(res,query(x<<11,mid+1,r,L,R));
return res;
}
int main(){
F.read(n);for(int i=1;i<=n;i++) F.read(a[i]);
for(int i=1;i<=n;i++) T[i]=(a[i-1]<=a[i])*T[i-1]+1,L[i]=max(L[i],T[i]);
for(int i=1;i<=n;i++) T[i]=(a[i-1]>=a[i])*T[i-1]+1,L[i]=max(L[i],T[i]);
for(int i=n;i>=1;i--) T[i]=(a[i+1]<=a[i])*T[i+1]+1,R[i]=max(R[i],T[i]);
for(int i=n;i>=1;i--) T[i]=(a[i+1]>=a[i])*T[i+1]+1,R[i]=max(R[i],T[i]);
build(1,1,n);F.read(q);for(int l,r;q--;){
F.read(l),F.read(r);
if(L[r]>=r-l+1) F.write(r-l+1);
else F.write(max(L[r],query(1,1,n,l,r-L[r])));
pc('\n');
}
return 0;
}