维护线段树上最长连续子段
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=200005;
int n,m;
struct tree{
int ml,mr,sum,lz;
}tr[maxn];
void pushup(int now,int l,int r)
{
tr[now].sum=max(tr[now<<1].mr+tr[now<<1|1].ml,max(tr[now<<1].sum,tr[now<<1|1].sum));
int mid=(l+r)>>1;
if(tr[now<<1].sum==mid-l+1)
tr[now].ml=tr[now<<1|1].ml+tr[now<<1].sum;
else tr[now].ml=tr[now<<1].ml;
if(tr[now<<1|1].sum==r-mid)
tr[now].mr=tr[now<<1].mr+tr[now<<1|1].sum;
else tr[now].mr=tr[now<<1|1].mr;
}
void build(int now,int l,int r)
{
if(l==r)
{
tr[now].ml=tr[now].mr=tr[now].sum=1;
tr[now].lz=-1;
return;
}
int mid=(l+r)>>1;
build(now<<1,l,mid);
build(now<<1|1,mid+1,r);
pushup(now,l,r);
return;
}
void pushdown(int now,int l,int r)
{
if(!tr[now].lz)
{
tr[now<<1].lz=tr[now<<1|1].lz=0;
int mid=(l+r)>>1;
tr[now<<1].sum=tr[now<<1].ml=tr[now<<1].mr=mid-l+1;
tr[now<<1|1].sum=tr[now<<1|1].ml=tr[now<<1|1].mr=r-mid;
}
else if(tr[now].lz==1)
{
tr[now<<1].lz=tr[now<<1|1].lz=1;
tr[now<<1].sum=tr[now<<1].ml=tr[now<<1].mr=0;
tr[now<<1|1].sum=tr[now<<1|1].ml=tr[now<<1|1].mr=0;
}
tr[now].lz=-1;
}
void update(int now,int l,int r,int x,int y,int val)
{
if(x<=l && r<=y)
{
if(val) tr[now].sum=tr[now].ml=tr[now].mr=0;
else tr[now].sum=tr[now].ml=tr[now].mr=r-l+1;
tr[now].lz=val;
return;
}
pushdown(now,l,r);
int mid=(l+r)>>1;
if(x<=mid) update(now<<1,l,mid,x,y,val);
if(y>mid) update(now<<1|1,mid+1,r,x,y,val);
pushup(now,l,r);
}
int query(int now,int l,int r,int x)
{
pushdown(now,l,r);
if(l==r) return l;
int mid=(l+r)>>1;
if(tr[now<<1].sum>=x) return query(now<<1,l,mid,x);
if(tr[now<<1].mr+tr[now<<1|1].ml>=x) return mid-tr[now<<1].mr+1;
return query(now<<1|1,mid+1,r,x);
}
int main()
{
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
scanf("%d%d",&n,&m);
int op,x,y;
build(1,1,n);
for(int i=1;i<=m;i++)
{
scanf("%d",&op);
if(op==1)
{
scanf("%d",&x);
if(tr[1].sum<x)
{
printf("0\n");
continue;
}
int t=query(1,1,n,x);
printf("%d\n",t);
update(1,1,n,t,t+x-1,1);
}
else
{
scanf("%d%d",&x,&y);
update(1,1,n,x,x+y-1,0);
}
}
return 0;
}