题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4348
大意
给定一个长为
N
N
N的
a
[
]
a[]
a[]数组,需要支持下列四种操作:
- 将 a [ l ] a[l] a[l]~ a [ r ] a[r] a[r]都增加 d d d,同时使时间戳 t + 1 t+1 t+1
- 查询当前 a [ l ] a[l] a[l]~ a [ r ] a[r] a[r]的和
- 查询时间戳为 t i t_i ti(保证 t i < t t_i<t ti<t)时 a [ l ] a[l] a[l]~ a [ r ] a[r] a[r]的和
- 将 a [ ] a[] a[]数组变为时间戳为 t i t_i ti时的状态(保证 t i < t t_i<t ti<t),同时将时间戳变为 t i t_i ti
思路
要求能还原状态,那么必然是可持久化数据结构了。区间查询/历史区间查询很容易想到用主席树,但是裸的主席树区间更新的复杂度是nlogn,所以参考线段树区间更新的lazy思想,给每个节点也加一个lazy标记。但主席树的lazy标记不能下推(否则会影响历史版本的主席树),所以在区间求和时不下推lazy标记而是将lazy标记的值乘上待查询区间长度加到求和的值中。
日常分不清查询区间和线段树节点的区间wa了一整版
特别注意
尽管主席树的lazy标记不能下推(否则会影响历史版本的主席树),但区间求和时仍然可以用不下推lazy标记而是将lazy标记的值乘上待查询区间长度加到求和的值中的方法来引入lazy标记,降低时间复杂度。
AC代码
#include<stdio.h>
#include<map>
#include<queue>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#define MOD 10000000007
#define N 100005
typedef long long LL;
using namespace std;
typedef struct node{
LL lson,rson,va,l,r,lazy;
}node;
LL tot,n,m,te,len,s,t,k,t2,l,r;
char mov[3];
LL a[N];
node tree[N<<5];
LL R[N];
LL time[N];
void init()
{
for(LL i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
}
void build(LL &root,LL l,LL r)
{
root=++tot;
tree[root].l=l;tree[root].r=r;
if(l==r)
{
tree[root].va=a[l];return;
}
LL mid=(l+r)/2;
build(tree[root].lson,l,mid);
build(tree[root].rson,mid+1,r);
tree[root].va=tree[tree[root].lson].va+tree[tree[root].rson].va;
return;
}
void insert(LL pre,LL &root,LL l,LL r,LL val)
{
tree[++tot]=tree[pre];root=tot;
if(tree[root].l==l&&tree[root].r==r)
{
tree[root].lazy+=val;
return;
}
LL mid=(tree[root].l+tree[root].r)/2;
if(l>mid) insert(tree[root].rson,tree[root].rson,l,r,val);
else if(r<=mid)insert(tree[root].lson,tree[root].lson,l,r,val);
else insert(tree[root].lson,tree[root].lson,l,mid,val),insert(tree[root].rson,tree[root].rson,mid+1,r,val);
tree[root].va=tree[tree[root].lson].va+tree[tree[root].rson].va+(mid-tree[root].l+1)*tree[tree[root].lson].lazy+(tree[root].r-mid)*tree[tree[root].rson].lazy;
return;
}
LL query(LL root,LL l,LL r,LL lazy)
{
if(tree[root].l==l&&tree[root].r==r)return tree[root].va+(r-l+1)*(lazy+tree[root].lazy);
LL mid=(tree[root].l+tree[root].r)/2;
if(l>mid) return query(tree[root].rson,l,r,lazy+tree[root].lazy);
else if(r<=mid)return query(tree[root].lson,l,r,lazy+tree[root].lazy);
else
{
LL c=query(tree[root].rson,mid+1,r,lazy+tree[root].lazy);
LL b=query(tree[root].lson,l,mid,lazy+tree[root].lazy);
return c+b;
}
}
int main()
{
while(scanf("%lld%lld",&n,&m)!=EOF)
{
init();
tot=0;t=0;
build(R[0],1,n);
time[0]=tot;
for(LL i=1;i<=m;i++)
{
scanf("%s",mov);
if(mov[0]=='C')
{
scanf("%lld%lld%lld",&l,&r,&s);insert(R[t],R[t+1],l,r,s);t++;time[t]=tot;
}
if(mov[0]=='Q')
{
scanf("%lld%lld",&l,&r);
printf("%lld\n",query(R[t],l,r,0));
}
if(mov[0]=='H')
{
scanf("%lld%lld%lld",&l,&r,&t2);
printf("%lld\n",query(R[t2],l,r,0));
}
if(mov[0]=='B')
{
scanf("%lld",&t2);
tot=time[t2];t=t2;
}
}
}
return 0;
}