线段树C-A Simple Problem with Integers(树懒线段树)

You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

Input

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input

10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4

Sample Output

4
55
9
15

Hint

The sums may exceed the range of 32-bit integers.
#include"stdio.h"
#include"cstdio"
#include"algorithm"
#define INF 0x3f3f3f3f
typedef long long ll;
const ll max_n=1e5+10;
ll A[max_n<<4],lazy[max_n<<4];
ll B[max_n];
using namespace std;
void init(ll l,ll r,ll rt)
{
    lazy[rt]=0; 
    if(l==r)
    {
        A[rt]=B[l];return ;
    }
    ll mid=(r+l)>>1;
    init(l,mid,rt<<1);
    init(mid+1,r,(rt<<1)|1);
    A[rt]=A[rt<<1]+A[(rt<<1)|1];
}
void down(ll rt,ll lens)
{
    if(lazy[rt])
    {
        lazy[rt<<1]+=lazy[rt];
        lazy[(rt<<1)|1]+=lazy[rt];
        A[rt<<1]+=lazy[rt]*(lens-(lens>>1));
        A[(rt<<1)|1]+=lazy[rt]*(lens>>1);
        lazy[rt]=0;
    }
}
ll query(ll L,ll R,ll l,ll r,ll rt)
{
    if(l>=L&&r<=R) return A[rt];
    down(rt,r-l+1);
    ll ans=0;
    ll mid=(l+r)>>1;
    if(L<=mid) ans+=query(L,R,l,mid,rt<<1);
    if(R>mid) ans+=query(L,R,mid+1,r,(rt<<1)|1);
    return ans;
}
void update(ll L,ll R,ll val,ll l,ll r,ll rt)
{
    if(l>=L&&r<=R)
    {
        lazy[rt]+=val;
        A[rt]+=val*(r-l+1);
        return ; 
    }
    down(rt,r-l+1);
    ll mid=(l+r)>>1;
    if(L<=mid) update(L,R,val,l,mid,rt<<1);
    if(R>mid) update(L,R,val,mid+1,r,(rt<<1)|1);
    A[rt]=A[rt<<1]+A[(rt<<1)|1];
}
int main() 
{
    ll n,q;
    while(scanf("%lld%lld",&n,&q)!=EOF)
    {
        ll i;
        for(i=1;i<=n;i++) scanf("%lld",&B[i]);
        init(1,n,1);
        char c[5];
        ll L,R;
        while(q--)
        {
            scanf("%s",c);
            if(c[0]=='Q')
            {
                scanf("%lld%lld",&L,&R);
                ll ret=query(L,R,1,n,1);
                printf("%lld\n",ret);
            }
            else
            {
                ll val;
                scanf("%lld%lld%lld",&L,&R,&val);
                update(L,R,val,1,n,1);
            }
        }
    }
}

 

posted @ 2017-03-30 13:07  lch316  阅读(256)  评论(0)    收藏  举报