您的位置:首页 > 其它

主席树区间修改模板

2017-10-22 10:16 288 查看
参考题目:hdu4348 To the moon

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = (int)3e6+10;
const int M = (int)1e5+10;
typedef long long ll;
int lson
,rson
,add
;
int Time
;
ll sum
;
int tot;

void copy(int x,int y){
lson[x] = lson[y];
rson[x] = rson[y];
add[x] = add[y];
sum[x] = sum[y];
}

inline void pushup(int root){
sum[root] = sum[lson[root]] + sum[rson[root]];
}

int build(int L,int R){
int now = ++tot;
add[now] = 0;
if(L==R){
cin>>sum[now];
lson[now] = rson[now] = 0;
return now;
}
int m=(L+R)>>1;
lson[now] = build(L,m);
rson[now] = build(m+1,R);
pushup(now);
return now;
}

int update(int root,int L,int R,int d,int l,int r){
int now = ++tot;
copy(now,root);
sum[now] += 1LL*d*(R-L+1);
if(L==l&&R==r){
add[now] += d;
return now;
}
int m = (l+r)>>1;
if(R<=m)
lson[now] = update(lson[root],L,R,d,l,m);
else if(L>m)
rson[now] = update(rson[root],L,R,d,m+1,r);
else{
lson[now] = update(lson[root],L,m,d,l,m);
rson[now] = update(rson[root],m+1,R,d,m+1,r);
}
return now;
}

ll query(int root,int L,int R,int l,int r){
ll ans = 1LL*add[root]*(R-L+1);
if(L==l&&R==r)return sum[root];
int m = (l+r)>>1;
if(R<=m)
ans+=query(lson[root],L,R,l,m);
else if(L>m)
ans+=query(rson[root],L,R,m+1,r);
else{
ans+=query(lson[root],L,m,l,m);
ans+=query(rson[root],m+1,R,m+1,r);
}
return ans;
}

int main(){
int n,m,l,r,d,t;
char op[5];
while(cin>>n>>m){
tot = 0;
Time[0] = build(1,n);
int now = 0;
while(m--){
scanf("%s",op);
if(op[0]=='Q'){
scanf("%d%d",&l,&r);
cout<<query(Time[now],l,r,1,n)<<endl;
}else if(op[0]=='C'){
scanf("%d%d%d",&l,&r,&d);
Time[now+1] = update(Time[now],l,r,d,1,n);
now++;
}else if(op[0]=='H'){
scanf("%d%d%d",&l,&r,&t);
cout<<query(Time[t],l,r,1,n)<<endl;
}else{
scanf("%d",&now);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: