poj 3468 线段树成段加减

Description

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
#include <iostream>
#include <cstdio>
#define lson l,m,2*rt
#define rson m+1,r,2*rt+1
using namespace std;

const int maxn = 100005;
long long tree[maxn*4];
long long add[maxn*4];
void pushUp(int rt)
{
    tree[rt]=tree[rt*2]+tree[rt*2+1];
}
void pushDown(int rt,int ln,int rn)
{
    if(add[rt])
    {
        add[rt*2]+=add[rt];
        add[rt*2+1]+=add[rt];
        tree[rt*2]+=add[rt]*ln;
        tree[rt*2+1]+=add[rt]*rn;
        add[rt]=0;
    }
}
void build(int l,int r,int rt)
{
    add[rt]=0;
    if(l==r)
    {
        scanf("%lld",&tree[rt]);
        return;
    }
    int m=(l+r)/2;
    build(lson);
    build(rson);

    pushUp(rt);
}
long long query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&r<=R)
        return tree[rt];
    int m=(l+r)/2;

    pushDown(rt,m-l+1,r-m);

    long long res=0;
    if(L<=m)
        res+=query(L,R,lson);
    if(R>m)
        res+=query(L,R,rson);
    return res;
}
void update(int L,int R,int c,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        tree[rt]+=(r-l+1)*c;
        add[rt]+=c;
        return;
    }
    int m=(l+r)/2;

    pushDown(rt,m-l+1,r-m);
    if(L<=m)
        update(L,R,c,lson);
    if(R>m)
        update(L,R,c,rson);
    pushUp(rt);
}
int main()
{
    int n,m;
    cin >> n >> m;
    build(1,n,1);
    char c;
    int a,b,d;
    while(m--)
    {
        cin >> c;
        if(c=='Q')
        {
            cin >> a >> b;
            cout << query(a,b,1,n,1) << endl;
        }
        else
        {
            cin >> a >> b >> d;
            update(a,b,d,1,n,1);
        }
    }
    return 0;
}

  

posted @ 2017-02-26 11:46  呆毛王王负剑  阅读(44)  评论(0)    收藏  举报