https://cn.vjudge.net/problem/POJ-3468
区间更新,区间查询
lazy 标记 每次更新查询都要把标记散掉

#include<iostream>
using namespace std;
typedef long long ll;
const int N=1e6;

struct node{
    int l,r;
    ll sum,lazy;
};
node tree[N*4];
int a[N];

void push_up(int root){
    tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
}

void push_down(int root){
    if(tree[root].lazy){
        tree[root<<1].sum+=(tree[root<<1].r-tree[root<<1].l+1)*tree[root].lazy;
        tree[root<<1|1].sum+=(tree[root<<1|1].r-tree[root<<1|1].l+1)*tree[root].lazy;
        tree[root<<1].lazy+=tree[root].lazy;
        tree[root<<1|1].lazy+=tree[root].lazy;
        tree[root].lazy=0;
    }
}

void build(int root,int l,int r){
    tree[root].l=l,tree[root].r=r,tree[root].lazy=0;
    if(l==r){
        tree[root].sum=a[l];
        return ;
    }
    int mid=(l+r)>>1;
    build(root<<1,l,mid);
    build(root<<1|1,mid+1,r);
    push_up(root);
}

void update(int root,int l,int r,int val){
    if(tree[root].l>=l && tree[root].r<=r){
        tree[root].lazy+=val;
        tree[root].sum+=1ll*val*(tree[root].r-tree[root].l+1); // 容易爆int
        return ;
    }
    push_down(root);
    int mid=(tree[root].l+tree[root].r)>>1;
    if(l<=mid) update(root<<1,l,r,val);
    if(r>=mid+1) update(root<<1|1,l,r,val);
    push_up(root);
}

ll query(int root,int l,int r){
    if(l<=tree[root].l && tree[root].r<=r) return tree[root].sum;
    push_down(root);
    ll val=0;
    int mid=(tree[root].l+tree[root].r)>>1;
    if(l<=mid) val+=query(root<<1,l,r);
    if(r>=mid+1) val+= query(root<<1|1,l,r);
    return val;
}
int main()
{
    int n,q;
    char op[2];

    while(~scanf("%d%d",&n,&q))
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);

        build(1,1,n);

        while(q--)
        {
            scanf(" %s",op);
            int a,b,c;
            if(op[0]=='C')
            {
                scanf("%d%d%d",&a,&b,&c);
                update(1,a,b,c);
            }

            else
            {
                scanf("%d%d",&a,&b);
                printf("%lld\n",query(1,a,b));
            }
        }
    }

    return 0;
}


 posted on 2019-08-21 20:57  谁是凶手1703  阅读(66)  评论(0)    收藏  举报