线段树(求区间和)

You have  N  integers,  A 1 A 2 , ... ,  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.
输入描述:
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.

输出描述:

You need to answer all Q commands in order. One answer in a line.
输入
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

输出

4
55
9
15

代码如下:
#include
#include
#include
#include
#define ll long long
using namespace std;

const int maxn=1e5+100;
struct note
{
    int left,right;
    ll flag;
    ll sum;
}tree[maxn*4];
ll a[maxn];

void pushup(int root)
{
    tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
}
void build(int l,int r,int root)
{
    tree[root].left=l;
    tree[root].right=r;
    tree[root].sum=0;
    tree[root].flag=0;
    if (l==r) {
        tree[root].sum=a[l];
        return ;
    }
    int mid=(l+r)>>1;
    build(l,mid,root<<1);
    build(mid+1,r,root<<1|1);
    pushup(root);
}
void pushdown(int root)
{
    if (tree[root].flag!=0) {
        tree[root<<1].sum+=tree[root].flag*(tree[root<<1].right-tree[root<<1].left+1);
        tree[root<<1|1].sum+=tree[root].flag*(tree[root<<1|1].right-tree[root<<1|1].left+1);
        tree[root<<1].flag+=tree[root].flag;
        tree[root<<1|1].flag+=tree[root].flag;
        tree[root].flag=0;
    }
}
ll query(int l,int r,int root)
{
    int left=tree[root].left;
    int right=tree[root].right;
    if (left>=l&&right<=r) {
        return tree[root].sum;
    }
    pushdown(root);
    int mid=(left+right)>>1;
    ll sum=0;
    if (mid>=r) sum+=query(l,r,root<<1);
    else if (l>mid) sum+=query(l,r,root<<1|1);
    else {
        sum+=query(l,mid,root<<1);
        sum+=query(mid+1,r,root<<1|1);
    }
    return sum;
}

void update(int l,int r,int root,int val)
{
    int left=tree[root].left;
    int right=tree[root].right;
    if (left>=l&&right<=r) {
        tree[root].sum+=val*(right-left+1);
        tree[root].flag+=val;
        return ;
    }
    pushdown(root);
    int mid=(left+right)>>1;
    if (r<=mid) update(l,r,root<<1,val);
    else if (l>=mid+1) update(l,r,root<<1|1,val);
    else {
        update(l,mid,root<<1,val);
        update(mid+1,r,root<<1|1,val);
    }
    pushup(root);
}
int main()
{
    int n,q;
    cin>>n>>q;
    for (int i=1;i<=n;i++) {
        cin>>a[i];
    }
    build(1,n,1);
    while (q--) {
        string str;
        cin>>str;
        if (str=="Q") {
            int l,r;
            cin>>l>>r;
            cout<>l>>r>>x;
            update(l,r,1,x);
        }
    }
    return 0;
}
































你可能感兴趣的:(数据结构)