数列操作

题目描述

这是一道模板题。

给定数列a[1], a[2], ..., a[n],你需要依次进行 q 个操作,操作有两类:

1 i x:给定 ,将 i 加上 x;
2 l r:给定 ,求 l 到 r 的和

输入格式

第一行包含 2 个正整数 ,表示数列长度和询问个数。保证 。
第二行 n 个整数 ,表示初始数列。保证 。
接下来 q 行,每行一个操作,为以下两种之一:

1 i x:给定 i,将 x 加上 ;
2 l r:给定 l, r,求 l到 r 的和。
保证 。

输出格式

对于每个 2 l r 操作输出一行,每行有一个整数,表示所求的结果。

样例

样例输入

3 2
1 2 3
1 2 0
2 1 3

样例输出

6

数据范围与提示

对于所有数据, , 。

思路

熟悉树状数组的模板,了解添加数据和求和的方法

代码

#include <cstdio>
#include <cstring>
int n, q;
long long arr[1000005];
inline int read() {
	int s = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-') f = -1;
		ch = getchar();		
	}
	while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return f * s;
}
int lowbit(int x) {
	return x & (-x);
}
void update(int x, int y) {
	for (; x <= n; x += lowbit(x)) {
		arr[x] += y;
	}
}
long long sum(int x) {
	long long res = 0;
	while (x >= 1) {
		res += arr[x];
		x -= lowbit(x);
	}
	return res;
}
int main() {
	n = read(), q = read();
	for (int i = 1, j; i <= n; ++i) {
		j = read();
		update(i, j);
		// printf("%d
", j);
	}
	for (int i = 1, a, b, c; i <= q; ++i) {
		a = read(), b = read(), c = read();
		if (a == 1) update(b, c);
		else printf("%lld
", sum(c) - sum(b - 1));
	}
	return 0;
}
原文地址:https://www.cnblogs.com/liuzz-20180701/p/11484675.html