Description
给定一个序列A[i],每次询问l,r,求[l,r]内最长子串,使得该子串为不上升子串或不下降子串
这道题目有两个思路:1、对原序列差分,转化为经典问题。2、线段树维护6个东西,分别是左边开始的最长不上升序列、最长不下降序列长度,右边开始的最长不上升序列、最长不下降序列长度,本段内最长不上升序列、最长不下降序列长度。我写了后面的。代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=50050;
int n,a[maxn];
int trlen=0;
struct Tree{int l,r,lc,rc,lup,ldown,rup,rdown,up,down;}tr[maxn*4];
Tree pushup(Tree lc,Tree rc,int L,int R,int l,int r)
{
Tree t;t.lc=L;t.rc=R;t.l=l;t.r=r;
if(lc.lup==lc.r-lc.l+1&&lc.r<=n&&a[lc.r]<=a[lc.r+1])
t.lup=lc.lup+rc.lup;
else t.lup=lc.lup;
if(lc.ldown==lc.r-lc.l+1&&lc.r<=n&&a[lc.r]>=a[lc.r+1])
t.ldown=lc.ldown+rc.ldown;
else t.ldown=lc.ldown;
if(rc.rup==rc.r-rc.l+1&&rc.l>1&&a[rc.l-1]>=a[rc.l])
t.rup=rc.rup+lc.rup;
else t.rup=rc.rup;
if(rc.rdown==rc.r-rc.l+1&&rc.l>1&&a[rc.l-1]<=a[rc.l])
t.rdown=rc.rdown+lc.rdown;
else t.rdown=rc.rdown;
t.up=max(lc.up,rc.up);
if(lc.r<=n&&a[lc.r]<=a[lc.r+1])t.up=max(t.up,lc.rdown+rc.lup);
t.down=max(lc.down,rc.down);
if(lc.r<=n&&a[lc.r]>=a[lc.r+1])t.down=max(t.down,lc.rup+rc.ldown);
return t;
}
void build(int l,int r)
{
int t=++trlen;
tr[t].l=l;tr[t].r=r;
if(l==r)tr[t].lup=tr[t].ldown=tr[t].rup=tr[t].rdown=tr[t].up=tr[t].down=1;
if(l<r)
{
int mid=l+r>>1;
int lc=trlen+1;build(l,mid);
int rc=trlen+1;build(mid+1,r);
tr[t]=pushup(tr[lc],tr[rc],lc,rc,l,r);
}
}
Tree query(int now,int l,int r)
{
if(tr[now].l==l&&tr[now].r==r)return tr[now];
int mid=tr[now].l+tr[now].r>>1,lc=tr[now].lc,rc=tr[now].rc;
if(r<=mid)return query(lc,l,r);
else if(l>mid)return query(rc,l,r);
else return pushup(query(lc,l,mid),query(rc,mid+1,r),tr[now].lc,tr[now].rc,tr[now].l,tr[now].r);
}
int main()
{
n=read();
for(int i=1;i<=n;i++)a[i]=read();
build(1,n);
int q=read();
while(q--)
{
int l=read(),r=read();
Tree ans=query(1,l,r);
printf("%d\n",max(ans.up,ans.down));
}
}