bzoj3212 Pku3468 A Simple Problem with Integers 线段树

时间:2021-09-11 15:44:40

3212: Pku3468 A Simple Problem with Integers

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 2046  Solved: 892
[ 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. 

 

水题 区间加法 区间求和
mmp我又忘了update后pushup

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define ls u<<1
#define rs ls|1
#define ll long long
#define N 100050
using namespace std;
int a[N],n,m;ll sum[N<<2],lz[N<<2];
void pushup(int u){sum[u]=sum[ls]+sum[rs];}
void build(int u,int l,int r){
    if(l==r){
        sum[u]=a[l];
        return;
    }
    int mid=l+r>>1;
    build(ls,l,mid);
    build(rs,mid+1,r);
    pushup(u);
}
void pushdown(int u,int L,int R){
    if(!lz[u])return;
    int mid=L+R>>1;
    lz[ls]+=lz[u];lz[rs]+=lz[u];
    sum[ls]+=lz[u]*(mid-L+1);
    sum[rs]+=lz[u]*(R-mid);
    lz[u]=0;
}
ll query(int u,int L,int R,int l,int r){
    if(l<=L&&R<=r)return sum[u];
    pushdown(u,L,R);
    int mid=L+R>>1;ll t=0;
    if(l<=mid)t+=query(ls,L,mid,l,r);
    if(r>mid)t+=query(rs,mid+1,R,l,r);
    return t;
}
void update(int u,int L,int R,int l,int r,int val){
    if(l<=L&&R<=r){
        sum[u]+=val*(R-L+1);
        lz[u]+=val;return;
    }
    pushdown(u,L,R);int mid=L+R>>1;
    if(l<=mid)update(ls,L,mid,l,r,val);
    if(r>mid)update(rs,mid+1,R,l,r,val);
    pushup(u);
}
int main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);
    build(1,1,n);
    char s[10];int l,r,v;
    while(m--){
        scanf("%s%d%d",s,&l,&r);
        if(s[0]=='Q'){
            printf("%lld",query(1,1,n,l,r));
            if(m)putchar('\n');
        }
        else scanf("%d",&v),update(1,1,n,l,r,v);
    }
    return 0;
}