跳到正文

算法·理论

树状数组

frzFRZ约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年4月22日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

树状数组简介

树状数组是一种支持 单点修改 和 区间查询 的,代码量小的数据结构。
普通树状数组维护的信息及运算要满足 结合律 且 可差分

树状数组原理


不难发现,c[x] 管辖的一定是一段右边界是 x 的区间总信息。
c[x] 的管辖范围是 [x−lowbit(x)+1,x][x-lowbit(x)+1,x]
lowbit(x) = x & -x

单点修改+区间查询

单点修改

1.初始令x′=x x' = x。
2.修改 c[x′]c[x']。
3.令 x′←x′+lowbit⁡(x′)x' \gets x' + \operatorname{lowbit}(x'),如果 x′>nx' > n 说明已经跳到尽头了,终止循环;否则回到第二步

C++
void add(int x, int k)
{
  while (x<=n)
  {  // 不能越界
    c[x]=c[x]+k;
    x=x+lowbit(x);
  }
  reutrn ;
}

区间查询

我们可以写出查询 a[1…x]a[1 \ldots x] 的过程:

从 c[x]c[x] 开始往前跳,有 c[x] 管辖 a[x−lowbit⁡(x)+1…x]a[x-\operatorname{lowbit}(x)+1 \ldots x];
令 x←x−lowbit⁡(x)x \gets x - \operatorname{lowbit}(x)
如果 x=0x = 0 说明已经跳到尽头了,终止循环;否则回到第一步。 将跳到的 cc 合并。

不难的出

∑i=lra[i]=c[r]−c[l−1]\sum_{i=l}^{r}a[i]=c[r]-c[l-1]
C++
int getsum(int x)
{  // a[1]..a[x]的和
  int ans = 0;
  while (x > 0)
  {
    ans = ans + c[x];
    x = x - lowbit(x);
  }
  return ans;
}

区间修改+单点查询

我们可以构建出原数组的差分数组 c[i],再用树状数组维护 c[i]

区间修改

对于修改操作,我们只用对 c[i] 操作即可
[L , R] + k —> add(L , k) + add(R + 1 , -k)

C++
void add(int pos,int k)
{
	while(pos<=n)
	{
		c[pos]+=k;
		pos+=lowbit(pos);
	}
	return ;
}
add(L,k);
add(R+1,-k);

单点查询

求出 c[i] 的前缀和即可

ak=∑i=1nc[i]a_k=\sum_{i=1}^{n}c[i]
C++
int ask(int pos)
{
	int ans=0;
	while(pos>0)
	{
		ans+=c[pos];
		pos-=lowbit(pos);
	}
	return ans;
}
原文