A Simple Problem with Integers (线段树,区间修改,lazy)

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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<iostream>
#include<cstdio> 
#include<cstring> 
#include<cstdlib> 
#include<cmath> 
#include<vector> 
#include<queue> 
#include<stack> 
#include<map> 
#include<set> 
#include<cmath>
#include<string> 
#include<iomanip> 
#include<ctime> 
#include<climits> 
#include<cctype> 
#include<algorithm>using  namespace std;
#define   mem(x,v)    memset(x,v,sizeof(x))
#define   lowbit(x)     (x&-x)

struct  node{
    int l,r,a,b;
    long long w,c;
}f[200009];
int t,n,x,y,z,m;
void build(int p,int a, int b){
    f[p].a = a; f[p].b = b;
    if (a+1 == b){
        scanf("%lld",&f[p].w);
        f[p].c = 0;
        return;
    }
    int mid = (a+ b)/2;
    t++; f[p].l = t; build(t,a,mid);
    t++; f[p].r = t; build(t,mid,b);
    f[p].w = f[f[p].l].w + f[f[p].r].w;
    f[p].c = 0;
    return;
}
void updata(int p){
    if (f[p].c==0) return;
    f[f[p].l].w +=(f[f[p].l].b-f[f[p].l].a)*f[p].c;
    f[f[p].l].c += f[p].c;
    f[f[p].r].w += (f[f[p].r].b-f[f[p].r].a)*f[p].c;
    f[f[p].r].c += f[p].c;
    f[p].c = 0;
    return;
}
void Insert(int p){
    if (x <= f[p].a && y >= f[p].b-1){
        f[p].c += z;
        f[p].w = f[p].w + (f[p].b-f[p].a)*z;
        return;
    }
    updata(p);
    int mid = (f[p].a+f[p].b)/2;
    if (x < mid) Insert(f[p].l);
    if (y >= mid) Insert(f[p].r);
    f[p].w = f[f[p].l].w+f[f[p].r].w;
    return;
}
long long  find(int p){
    long long sum = 0;
    if (x <= f[p].a && y >= f[p].b-1){
        return f[p].w;
    }
    updata(p);
    int mid = (f[p].a+f[p].b)/2;
    if (x < mid) sum += find(f[p].l);
    if (y >= mid) sum += find(f[p].r);
    f[p].w = f[f[p].l].w+f[f[p].r].w;
    return sum;
}
int main() {
    char st;
    scanf("%d%d", &n,&m);
    t = 1;
    build(1, 1, n + 1);
    for (int i= 0; i < m; i++){
        scanf("%c",&st);
        scanf("%c",&st);
        if (st == 'Q'){
            scanf("%d%d",&x,&y);
            printf("%lld\n",find(1));
        } else
        {
            scanf("%d%d%d",&x,&y,&z);
            Insert(1);
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/80491613