hdu 1540

题目

以前一直以为线段树区间合并是什么新奇的玩意,原来以前做过的区间最大子序列和就是区间合并的一种,都是毒瘤题……

#include
#include
#include
#include
#include
#include
#include 
#include
#include
#include 
#include
#include
#include
#include
#include
#define IO ios::sync_with_stdio(false)
#define eps 1e-7
#define int long long
using namespace std;
const int N=100000+100;
struct node
{
	int l,r,ll,rr,ml;
}t[N*4];
stack<int>s;
char c;
int n,m;
void build(int rt,int l,int r)
{
	t[rt].l=l,t[rt].r=r;
	t[rt].ll=r-l+1,t[rt].rr=r-l+1,t[rt].ml=r-l+1;
	if(l==r)
	{
		return;
	}
	int mid=l+r>>1;
	build(rt*2,l,mid);
	build(rt*2+1,mid+1,r);
}
void upd(int rt,int x,int v)
{
	if(t[rt].l==t[rt].r)
	{
		t[rt].ll=t[rt].ml=t[rt].rr=v;
		return;
	}
	int mid=t[rt].l+t[rt].r>>1;
	if(x<=mid)
	{
		upd(rt*2,x,v);
	}
	else
	{
		upd(rt*2+1,x,v);
	}
	t[rt].ml=max(t[rt*2].ml,t[rt*2+1].ml);
	t[rt].ml=max(t[rt].ml,t[rt*2].rr+t[rt*2+1].ll);
	t[rt].ll=t[rt*2].ll;
	if(t[rt].ll==t[rt*2].r-t[rt*2].l+1)
	{
		t[rt].ll+=t[rt*2+1].ll;
	}
	t[rt].rr=t[rt*2+1].rr;
	if(t[rt].rr==t[rt*2+1].r-t[rt*2+1].l+1)
	{
		t[rt].rr+=t[rt*2].rr;
	}
}
int ask(int rt,int x)
{
	if(t[rt].l==t[rt].r||t[rt].ml==t[rt].r-t[rt].l+1||t[rt].ml==0)return t[rt].ml;
	int mid=t[rt].l+t[rt].r>>1;
	if(x<=mid)
	{
		if(x>=mid-t[rt*2].rr+1)
		{
			return ask(rt*2,x)+ask(rt*2+1,mid+1);
		}
		else
		{
			return ask(rt*2,x);
		}
	}
	else
	{
		if(x<=mid+t[rt*2+1].ll)
		{
			return ask(rt*2,mid)+ask(rt*2+1,x);
		}
		else
		{
			return ask(rt*2+1,x);
		}
	}
}
signed main()
{
	IO;
	while(cin>>n>>m)
	{
		while(!s.empty())s.pop();
		//cin>>n>>m;
	build(1,1,n);
	for(int i=1;i<=m;i++)
	{
		cin>>c;
		if(c=='D')
		{
			int x;
			cin>>x;
			s.push(x);
			upd(1,x,0);
		}
		if(c=='Q')
		{
			int x;
			cin>>x;
			cout<<ask(1,x)<<endl;
		}
		if(c=='R')
		{
			if(s.size()==0)continue;
			upd(1,s.top(),1);
			s.pop();
		}
	}
	}
}

你可能感兴趣的:(线段树)