HDU 4348 To the moon [主席树 区间修改]

题意:给你长度为n的数组,共有四个操作:

1.对区间【L,R】增加d,并时间增加1   

2.询问当前时间的区间【L,R】的和

3.询问时间为T时的区间【L,R】的和

4.返回到时间为T的时候

题解:既然有历史版本,肯定是用主席树了,但是主席树的区间的修改,一种办法是在遇到有延迟更新的区间的时候重新开左右儿子来pushdown 标记,但是这题严格一点的数据就能把他卡成空间为n*n*logn。所以还有一种办法就是,永久化标记,不pushdown,这时候就可以大大节省空间了,nlogn的空间复杂度。

AC代码:

#include<stdio.h>
#include<algorithm>
#include<map>
using namespace std;
#define N 100005
typedef long long ll;
ll a[N];
ll tree[N*25],add[N*25];
int root[N*25],lchild[N*25],rchild[N*25];
int tot;
void build(int L,int R,int root)
{
	add[root]=0;
	if(L==R)
	{
		tree[root]=a[L];
		return ;
	}
	int mid=L+R>>1;
	build(L,mid,lchild[root]=++tot);
	build(mid+1,R,rchild[root]=++tot);
	tree[root]=tree[lchild[root]]+tree[rchild[root]];
}
void update(int last,int cur,int l,int r,int L,int R,ll k)
{
	tree[cur]=tree[last]+(r-l+1)*k;
	lchild[cur]=lchild[last];
	rchild[cur]=rchild[last];
	add[cur]=add[last];
	if(l<=L&&R<=r)
	{
		add[cur]+=k;
		return ;
	}
	int mid=L+R>>1;
	if(r<=mid)update(lchild[last],lchild[cur]=++tot,l,r,L,mid,k);
	else if(l>mid)update(rchild[last],rchild[cur]=++tot,l,r,mid+1,R,k);
	else 
	{
		update(lchild[last],lchild[cur]=++tot,l,mid,L,mid,k);
		update(rchild[last],rchild[cur]=++tot,mid+1,r,mid+1,R,k);
	}
}
ll query(int root,int l,int r,int L,int R,ll ad)
{
	if(l<=L&&R<=r)
		return tree[root]+(r-l+1)*ad;
	int mid=L+R>>1;
	if(r<=mid)return query(lchild[root],l,r,L,mid,ad+add[root]);
	else if(l>mid)return query(rchild[root],l,r,mid+1,R,ad+add[root]);
	else return	query(lchild[root],l,mid,L,mid,ad+add[root])+query(rchild[root],mid+1,r,mid+1,R,ad+add[root]);
}
int main()
{
	int n,m;
	while(~scanf("%d%d",&n,&m))
	{
		tot=0;
		for(int i=1;i<=n;i++)
			scanf("%lld",&a[i]);
		build(1,n,root[1]=++tot);
		int time=1;
		for(int i=0;i<m;i++)
		{
			char op[2];
			scanf("%s",op);
			if(op[0]=='C')
			{
				int l,r;
				ll k;
				scanf("%d%d%lld",&l,&r,&k);
				time++;
				update(root[time-1],root[time]=++tot,l,r,1,n,k);
			}
			else if(op[0]=='Q')
			{
				int l,r;
				scanf("%d%d",&l,&r);
				printf("%lld\n",query(root[time],l,r,1,n,0));
			}
			else if(op[0]=='H')
			{
				int l,r,t;
				scanf("%d%d%d",&l,&r,&t);
				t++;
				printf("%lld\n",query(root[t],l,r,1,n,0));
			}
			else if(op[0]=='B')
			{
				int t;
				scanf("%d",&t);
				time=t+1;
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值