A Simple Problem with Integers 区间更新和查询

来源:互联网 发布:东方的漫画软件 编辑:程序博客网 时间:2024/05/29 19:16

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 51 2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4

Sample Output

455915


标准的模板题,结果我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;  }  


阅读全文
0 0
原创粉丝点击