1. 程式人生 > >A Simple Problem with Integers 區間更新和查詢

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

標準的模板題,結果我debug了大半天!最終結果是我錯寫了一個字母!!!QAQ

#include <iostream>  
#include <algorithm>  
#include <cstdio>  
#include <cstring>

using namespace std;  
const int N = 1e5 + 5;

struct tree
{
    int l, r;
    long long sum, add;
}STree[N << 2];

long long ans;

void Build(int l, int r, int k)
{
    STree[k].l = l;
    STree[k].r = r;
    STree[k].add = 0;
    if(l == r)
    {
        scanf("%lld", &STree[k].sum);
        return;
    }
    int mid = (l + r) >> 1;
    Build(l, mid, k << 1);
    Build(mid + 1, r, k << 1 | 1);
    STree[k].sum = STree[k << 1].sum + STree[k << 1 | 1].sum;
}
void Push_down(int k, int m)
{
    if(STree[k].add)
    {
        STree[k << 1].add += STree[k].add;
        STree[k << 1 | 1].add += STree[k].add;
        STree[k << 1].sum += STree[k].add * (m - (m >> 1));
        STree[k << 1 | 1].sum += STree[k].add * (m >> 1); 
        STree[k].add = 0;
    }
}
void Update(int k, int a, int b, int c)
{
    if(a <= STree[k].l && b >= STree[k].r)
    {
        STree[k].add += c;
        STree[k].sum += (STree[k].r - STree[k].l + 1) * c; //就是這裡!我把後面的l寫成r了...
        return;
    }
    Push_down(k, STree[k].r - STree[k].l + 1);
    int mid = (STree[k].l + STree[k].r) >> 1;
    if(a <= mid)
        Update(k << 1, a, b, c);
    if(b > mid)
        Update(k << 1 | 1, a, b, c);
    STree[k].sum = STree[k << 1].sum + STree[k << 1 | 1].sum;
}
void Query(int k, int a, int b)
{
    if(STree[k].l >= a && STree[k].r <= b)
    {
        ans += STree[k].sum;
        return;
    }
    Push_down(k, STree[k].r - STree[k].l + 1);
    int mid = (STree[k].l + STree[k].r) >> 1;
    if(a <= mid)
        Query(k << 1, a, b);
    if(b > mid)
        Query(k << 1 | 1, a, b);
}
int main()  
{         
    int n, q, a, b, c;
    char s[2];
    scanf("%d%d", &n, &q);
    Build(1, n, 1);
    while(q--)
    {
        scanf("%s%d%d", s, &a, &b);
        if(s[0] == 'Q')
        {
            ans = 0;
            Query(1, a, b);
            printf("%lld\n", ans);
        }
        else
        {
            scanf("%d", &c);
            Update(1, a, b, c);
        }
    }
    return 0;  
}