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;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/110151697
今日推荐