Interval summation

Title Description

Given a sequence of numbers, there are two operations, one is to modify an element, the other is to find the continuous sum of intervals.

input

The first line of input data contains two positive integers n, m (n<=100000, m<=500000), and the following is m line.

output

Each row has three positive integers k,a,b(k=0 or 1, a,b <= n). k = 0 denotes the sum of all the numbers in the query interval [a,b], when the number at a is added to b, and K = 1. Output the corresponding answer for each query.

sample input

10 20
0 1 10
1 1 4
0 6 6
1 4 10
1 8 9
1 4 9
0 10 2
1 1 8
0 2 10
1 3 9
0 7 8
0 3 10
0 1 1
1 3 8
1 6 9
0 5 5
1 1 8
0 4 2
1 2 8
0 1 1

sample output

10
6
0
6
16
6
24
14
50
41

Title Solution

This problem is a template problem, as long as you pay attention to the initial value of the node is 0.

#include<iostream>
using namespace std; 
const int maxn=1e5+10;
#define ll long long 
ll sum[maxn*4];//Four times the space
ll query(int x,int y,int l,int r,int rt)
{
    if(x<=l&&y>=r)//If the current interval is included in the interval to be queried, the sum is taken directly.
        return sum[rt];
    ll ans=0;
    int mid=(l+r)/2;
    if(x<=mid)
        ans+=query(x,y,l,mid,2*rt);
    if(y>mid)
        ans+=query(x,y,mid+1,r,2*rt+1);
    return ans;
}
void update(int x,int y,int l,int r,int rt)
{
    if(l==r)
    {
        sum[rt]+=y;
        return;
    }
    int mid=(l+r)/2;
    if(x<=mid)
        update(x,y,l,mid,2*rt);
    else
        update(x,y,mid+1,r,2*rt+1);
    sum[rt]=sum[2*rt]+sum[2*rt+1];
}
void build(int l,int r,int rt)//The number rt node contains an interval of [l,r]
{
    sum[rt]=0;//Initialization is 0
    if(l==r)
        return ;
    int mid=(l+r)/2;
    build(l,mid,2*rt);
    build(mid+1,r,2*rt+1);
    sum[rt]=sum[2*rt]+sum[2*rt+1];
}
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    build(1,n,1);
    while(m--)
    {
        int k,a,b;
        scanf("%d%d%d",&k,&a,&b);
        if(k==1)
        {
            printf("%lld\n",query(a,b,1,n,1));
        }
        else if(k==0)
        {
            update(a,b,1,n,1);
        }
    }
    return 0;
}

 

Posted by tfburges on Sun, 13 Oct 2019 13:22:41 -0700