hdu 4348 To the moon (主席树)

题意 给你一些操作让你实现

题解:主要是主席树至于对于区间更新有两种方式一种是打lazy 下传标记,另外一种是直接记录每走一层就把这层的lazy标记加上,这样就可以实现节约空间。

#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[N],rson[N],add[N];
int Time[N];
ll sum[N];
int total;
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 = ++total;
    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 = ++total;
    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){
        total = 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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值