[模板] 洛谷 P3374 树状数组 1

题目描述

如题,已知一个数列,你需要进行下面两种操作:

  • 将某一个数加上 x
  • 求出某区间每一个数的和

输入格式

第一行包含两个正整数 n,m,分别表示该数列数字的个数和操作的总个数。

第二行包含 n 个用空格分隔的整数,其中第 i 个数字表示数列第 i 项的初始值。

接下来 m 行每行包含 3 个整数,表示一个操作,具体如下:

  • 1 x k 含义:将第 x 个数加上 k
  • 2 x y 含义:输出区间 [x,y] 内每个数的和

输出格式

输出包含若干行整数,即为所有操作 2 的结果。

输入输出样例

输入 #1

5 5
1 5 4 2 3
1 1 3
2 2 5
1 3 -1
1 4 2
2 1 4

输出 #1

14
16

说明/提示

【数据范围】

对于 30% 的数据,1≤n≤8,1≤m≤10;
对于 70% 的数据,1≤n,m≤10^4;
对于 100% 的数据,1≤n,m≤5×10^5。

样例说明:

img

故输出结果14、16

代码

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

int read() {
    int x = 0; bool f = 0; char ch = getchar();
    while (!isdigit(ch)) f = (ch == 45), ch = getchar();
    while ( isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    return f ? (~x + 1) : x;
}

int n, m;
int a[MAXN] = {0};

void Add(int pos, int val) {
    while (pos <= n) {
        a[pos] += val;
        pos += pos & (-pos);
    }
}

int Sum(int pos) {
    int sum = 0;
    while (pos > 0) {
        sum += a[pos];
        pos -= pos & (-pos);
    }
    return sum;
}

int main() {
    n = read(); m = read();
    for (int i = 1, x; i <= n; i++) {
        x = read();
        Add(i, x);
    }
    for (int i = 1, x, y, z; i <= m; i++) {
        x = read(); y = read(); z = read();
        if (x == 1) Add(y, z);
        if (x == 2) cout << Sum(z) - Sum(y - 1) << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值