跳到正文

算法·理论

树状数组

yyycj约 6 分钟
原文

这是 2025年11月8日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年9月28日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

树状数组可用于动态查询数组的前缀和,其支持单点修改、区间修改、单点查询、区间查询操作。

树状数组的根本思想其实是分块,把每个区间分成最多 log⁡n\log n 个区间,这样查询的复杂度即 log⁡n\log n。

我们可以这样分块,观察 1010 这个数,(10)10=(1010)2(10)_{10}=(1010)_{2},那么我们就可以将树状数组的第 1010 个数看做树状数组的第 1010 个数和第 88 个数的和,我们可以发现这分别是 1010 的二进制不减去任何数和减去最低位 11 的权值的数。按照此规律,每个数都这么算,最终就能得到一个树状数组。具体地:

其中 a 表示原数组,c 表示树状数组。

那么我们如何得到这个数的二进制中 11 的权值呢?这就是树状数组的核心操作 lowbit⁡(x)\operatorname{lowbit}(x),它表示 xx 中最低位 11 的权值,有了它我们只需每次先使答案增加 cxc_{x},然后 x←x−lowbit⁡(x)x \gets x-\operatorname{lowbit}(x),直到 xx 为 00。这就是 query 操作。

而对于单点修改,其实就是区间查询的逆运算,不难发现只要每次先 cx←cx+kc_{x} \gets c_{x}+k,然后 x←x+lowbit⁡(x)x \gets x +\operatorname{lowbit}(x) 即可。这就是 update 操作。

然后对于区间修改,我们可以对树状数组进行差分,这样就可以进行单点查询。如果要区间修改与区间查询,可使用线段树。

Code

C++
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

#ifdef ONLINE_JUDGE
char buf[1 << 20], *p1, *p2;
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 20, stdin), p1 == p2) ? 0 : *p1++)
// #define getchar getchar_unlocked
#endif
template<typename T> void read(T &x) { int f = 1; x = 0; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-')f = -1; ch = getchar(); }while (isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }x *= f; }
template<typename T, typename ...Args> void read(T &x, Args &...args) { read(x); read(args...); }int man();int main(){return man();}
template<typename T> void print(T x) { if (x < 0) { putchar('-'); x = -x; }if (x > 9) { print(x / 10); }putchar(char(x % 10 + 48)); }
template<typename T, typename ...Args> void print(T x, Args ...args) { print(x); putchar(' '); print(args...); }

#define OUT 0
#define MAMBA return
const int N = 5e5 + 10;
const int INT_INF = 0x3f3f3f3f;
const long long LL_INF = 0x3f3f3f3f3f3f3f3f;
template<typename T1, typename T2> T1 _pow(T1 a, T2 b) { T1 x = 1, y = a; while(b > 0) {if (b & 1) x *= y; y *= y; b >>= 1; } return x; }
// ----------------------------

// ----------------------------
long long a[N], sum[N];
// ----------------------------
int lowbit(int x) {
	return (x & -x);
}

long long query(int x) {
	long long res = 0;
	while (x) {
		res += sum[x];
		x -= lowbit(x);
	}
	return res;
}

void update(int x, int k, int n) {
	while (x <= n) {
		sum[x] += k;
		x += lowbit(x);
	}
}

int man() {
	int n, m; read(n, m);
	for (int i = 1; i <= n; i++) {
		read(a[i]);
		update(i, a[i], n);
	}
	// ----------------------------
	int op, x, k, y;
	while (m--) {
		read(op);
		if (op == 1) {
			read(x, k);
			update(x, k, n);
		}
		else {
			read(x, y);
			print(query(y) - query(x - 1));
			putchar('\n');
		}
	}
	// ----------------------------
	
	MAMBA OUT;
}
/*
				 .-~~~~~~~~~-._       _.-~~~~~~~~~-.
			 __.'              ~.   .~              `.__
		   .'//   A    C    之   \./  之    真    理  \`.
		 .'//                     |                     \`.
	   .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \`.
	 .'//.-"                 `-.  |  .-'                 "-.\`.
   .'//______.============-..   \ | /   ..-============.______\`.
 .'______________________________\|/______________________________`.
*/