【线段树】P2894 [USACO08FEB]Hotel G

维护线段树上最长连续子段

 

 

代码

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值