天天看點

【nowcoder】Big Water Problem(線段樹,單點更新,區間求和)

連結:https://www.nowcoder.com/acm/contest/77/B

來源:牛客網

時間限制:C/C++ 1秒,其他語言2秒

空間限制:C/C++ 131072K,其他語言262144K

64bit IO Format: %lld

題目描述

給一個數列,會有多次詢問,對于每一次詢問,會有兩種操作:

1:給定兩個整數x, y, 然後在原數組的第x位置上加y;

2:給定兩個整數l,r,然後輸出數組從第l位加到第r位數字的和并換行

輸入描述:

第一行有兩個整數n, m(1 <= n, m <= 100000)代表數列的長度和詢問的次數

第二行n個數字,對于第i個數字a[i],(0<=a[i]<=100000)。

接下來m行,每一行有三個整數f, x, y。第一個整數f是1或者是2,代表操作類型,如果是1,接下來兩個數x,y代表第x的位置上加y,如果是2,則求x到y的和,保證資料合法。

輸出描述:

輸出每次求和的結果并換行

示例1

輸入

10 2

1 2 3 4 5 6 7 8 9 10

1 1 9

2 1 10

輸出

64

分析:單點更新,區間求和

#include <bits/stdc++.h>
using namespace std;

#define mem(a,n) memset(a,n,sizeof(a))
#define memc(a,b) memcpy(a,b,sizeof(b))
#define rep(i,a,n) for(int i=a;i<n;i++) ///[a,n)
#define dec(i,n,a) for(int i=n;i>=a;i--)///[n,a]
#define pb push_back
#define fi first
#define se second
#define IO ios::sync_with_stdio(false)
#define fre freopen("in.txt","r",stdin)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
typedef unsigned long long ull;
const double PI=acos(-);
const double E=;
const double eps=;
const int INF=;
const int MOD=;
const int N=+;
const ll maxn=+;
const int dir[][]= {-,,,,,-,,};
int sum[N<<],a[N];
void pushup(int rt)
{
    sum[rt]=sum[rt<<]+sum[rt<<|];
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&sum[rt]);
        return ;
    }
    int m=(l+r)>>;
    build(lson);
    build(rson);
    pushup(rt);
}
void update(int p,int c,int l,int r,int rt)
{
    if(l==r)
    {
        sum[rt]+=c;
        return ;
    }
    int m=(l+r)>>;
    if(p<=m)
        update(p,c,lson);
    else
        update(p,c,rson);
    pushup(rt);
}
int query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        return sum[rt];
    }
    int m=(l+r)>>;
    int ret=;
    if(L<=m)
        ret+=query(L,R,lson);
    if(R>m)
        ret+=query(L,R,rson);
    return ret;
}
int main()
{
    int n,q;
    scanf("%d%d",&n,&q);
    build(,n,);
    int op,a,b;
    while(q--)
    {
        scanf("%d%d%d",&op,&a,&b);
        if(op==)
            update(a,b,,n,);
        else
        {
            int ans=query(a,b,,n,);
            printf("%d\n",ans);
        }
    }
    return ;
}