A Simple Problem with Integers——区间查询、区间修改模板题

题目链接

题意:

C a b c  【a,b】区间都加c

Q a b   查询【a,b】的区间和

题解:

区间修改+区间查询 模板题

代码:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
struct node
{
    int l,r;
    ll sum,lazy;
    void update(ll x)
    {
        sum+=1ll*(r-l+1)*x;
        lazy+=x;
    }
}tree[maxn<<2];
int n,m,a[maxn];
void push_up(int x)
{
    tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum;
}
void push_down(int x)
{
    ll lazyval=tree[x].lazy;
    if(lazyval)
    {
        tree[x<<1].update(lazyval);
        tree[x<<1|1].update(lazyval);
        tree[x].lazy=0;
    }
}
void build(int x,int l,int r)
{
    tree[x].l=l,tree[x].r=r;
    tree[x].lazy=tree[x].sum=0;
    if(l==r)tree[x].sum=a[l];
    else
    {
        int mid=(l+r)>>1;
        build(x<<1,l,mid);
        build(x<<1|1,mid+1,r);
        push_up(x);
    }

}
void update(int x,int l,int r,ll val)
{
    int L=tree[x].l,R=tree[x].r;
    if(l<=L && R<=r)tree[x].update(val);
    else
    {
        push_down(x);
        int mid=(L+R)>>1;
        if(mid>=l)update(x<<1,l,r,val);
        if(mid<r)update(x<<1|1,l,r,val);
        push_up(x);
    }
}
ll query(int x,int l,int r)
{
    
    int L=tree[x].l,R=tree[x].r;
    if(l<=L && R<=r)return tree[x].sum;
    else
    {
        ll ans=0;
        push_down(x);
        int mid=(L+R)>>1;
        if(mid>=l)ans+=query(x<<1,l,r);
        if(mid<r)ans+=query(x<<1|1,l,r);
        push_up(x);
        return ans;
    }
    

}
int main()
{
    int n,m;;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    build(1,1,n);
    while(m--)
    {
        char op;
        cin>>op;
        if(op=='C')
        {
            int a,b;
            ll c;
            scanf("%d%d%lld",&a,&b,&c);
            update(1,a,b,c);
        }
        else
        {
            int a,b;
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(1,a,b));
        }
    }

    return 0;
}
View Code

 

posted @ 2019-10-02 14:27  。小姜  阅读(204)  评论(0编辑  收藏  举报