题目描述
如题,已知一个数列,你需要进行下面两种操作:
- 将某一个数加上 x
- 求出某区间每一个数的和
输入格式
第一行包含两个正整数 n,m,分别表示该数列数字的个数和操作的总个数。
第二行包含 n 个用空格分隔的整数,其中第 i 个数字表示数列第 i 项的初始值。
接下来 m 行每行包含 3 个整数,表示一个操作,具体如下:
1 x k
含义:将第 x 个数加上 k2 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。
样例说明:
故输出结果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;
}