Live2d Test Env

BZOJ3212: Pku3468 A Simple Problem with Integers(线段树)

3212: Pku3468 A Simple Problem with Integers

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 2530  Solved: 1096
[Submit][Status][Discuss]

Description


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<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
using namespace std;
const int maxn=400010;
int Lazy[maxn]; ll sum[maxn];
void pushup(int Now){ sum[Now]=sum[Now<<1]+sum[Now<<1|1];}
void pushdown(int Now,int L,int R){
    if(Lazy[Now]){
        int Mid=(L+R)>>1;
        sum[Now<<1]+=(ll)Lazy[Now]*(Mid-L+1);
        sum[Now<<1|1]+=(ll)Lazy[Now]*(R-Mid);
        Lazy[Now<<1]+=Lazy[Now];
        Lazy[Now<<1|1]+=Lazy[Now];
        Lazy[Now]=0;
    }
}
void build(int Now,int L,int R)
{
    if(L==R) {
        scanf("%lld",&sum[Now]);
        return ;
    }
    int Mid=(L+R)>>1;
    build(Now<<1,L,Mid); build(Now<<1|1,Mid+1,R);
    pushup(Now);
}
ll query(int Now,int L,int R,int l,int r)
{
    if(l<=L&&r>=R) return sum[Now];
    int Mid=(L+R)>>1; ll res=0;
    pushdown(Now,L,R);
    if(l<=Mid) res+=query(Now<<1,L,Mid,l,r);
    if(r>Mid) res+=query(Now<<1|1,Mid+1,R,l,r);
    pushup(Now);
    return res;
}
void update(int Now,int L,int R,int l,int r,int c)
{
    if(l<=L&&r>=R){ sum[Now]+=(ll)(R-L+1)*c; Lazy[Now]+=c; return ;}
    int Mid=(L+R)>>1; pushdown(Now,L,R);
    if(l<=Mid) update(Now<<1,L,Mid,l,r,c);
    if(r>Mid) update(Now<<1|1,Mid+1,R,l,r,c);
    pushup(Now);
}
int main()
{
    int N,M,L,R,x; char opt[3];
    scanf("%d%d",&N,&M);
    build(1,1,N);
    rep(i,1,M){
        scanf("%s%d%d",opt,&L,&R);
        if(opt[0]=='Q') printf("%lld\n",query(1,1,N,L,R));
        else scanf("%d",&x),update(1,1,N,L,R,x);
    }
    return 0;
}

 

posted @ 2018-11-20 18:59  nimphy  阅读(198)  评论(0编辑  收藏  举报