HDU 4348 To the moon(主席树区间更新)

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+1000;
typedef int LL;
struct Tree{
   LL lson,rson,tag;long long sum;///动态开点的话,lson和rson分别代表左右儿子区间的序号,而之前我的静态的写法l,r分别代表区间端点,p代表区间编号
}tree[4*1000000+10];
LL root[4*1000000+10],a[4*1000000+10];
LL tot;
LL build(LL l,LL r){
   LL rt=++tot;
   tree[rt].tag=0;
   if(l==r){
      tree[rt].sum=a[l];return rt;
   }
   LL mid=(l+r)>>1;
   tree[rt].lson=build(l,mid);
   tree[rt].rson=build(mid+1,r);
   tree[rt].sum=tree[tree[rt].lson].sum+tree[tree[rt].rson].sum;
   return rt;
}
LL update(LL pre,LL l,LL r,LL A,LL B,long long d){
   LL rt=++tot;
   tree[rt].lson=tree[pre].lson;
   tree[rt].rson=tree[pre].rson;
   tree[rt].tag=tree[pre].tag;
   tree[rt].sum=tree[pre].sum;
   if(A<=l&&B>=r){
        tree[rt].tag+=d;
        tree[rt].sum+=(LL)(r-l+1)*d;
        return rt;
   }
   LL mid=(l+r)>>1;
   if(A<=mid) tree[rt].lson=update(tree[pre].lson,l,mid,A,B,d);
   if(B>mid) tree[rt].rson=update(tree[pre].rson,mid+1,r,A,B,d);
   tree[rt].sum=tree[tree[rt].lson].sum+tree[tree[rt].rson].sum+(r-l+1)*tree[rt].tag;
   return rt;
}
long long query(LL p,LL l,LL r,LL A,LL B){
    if(A<=l&&B>=r){
        return tree[p].sum;
    }
    long long res=0;
    if(l<=A){
        if(r>=B) res+=(B-A+1)*tree[p].tag;
        else res+=(r-A+1)*tree[p].tag;
    }
    else res+=(B-l+1)*tree[p].tag;
    LL mid=(l+r)>>1;
    if(A<=mid) res+=query(tree[p].lson,l,mid,A,B);
    if(B>mid) res+=query(tree[p].rson,mid+1,r,A,B);
    return res;
}
int main(void)
{
  ///cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,m;
  LL now;
  char ch[10];
  while(~scanf("%d%d",&n,&m)){
    tot=now=1;
    for(LL i=1;i<=n;i++){scanf("%d",&a[i]);}
    root[now]=build(1,n);///初始状态的树
    while(m--){
        scanf("%s",ch);
        if(ch[0]=='Q'){
            LL A,B;scanf("%d%d",&A,&B);
            printf("%lld\n",query(root[now],1,n,A,B));
        }
        else if(ch[0]=='C'){
            LL A,B;long long C;scanf("%d%d%lld",&A,&B,&C);
            root[now+1]=update(root[now],1,n,A,B,C);
            now++;
        }
        else if(ch[0]=='H'){
            LL l,r,t;scanf("%d%d%d",&l,&r,&t);
            printf("%lld\n",query(root[t+1],1,n,l,r));
        }
        else if(ch[0]=='B'){
            scanf("%d",&now);
            now++;
        }
    }
  }
return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值