PrevNext

树状数组

它的实现比线段树更短,但初看时可能更难理解。

资源

Resources
CSA

交互式演示

CPH

与上文类似

cp-algo

同样与上文类似

TC

动态区间和查询

实现

class BIT:
"""
Short for "binary indexed tree",
this data structure supports point update and range sum
queries like a segment tree.
"""
def __init__(self, len_: int) -> None:
self.bit = [0] * (len_ + 1)
self.arr = [0] * len_

寻找第 kk 个元素

假设需要一种数据结构,它除了支持 C++ set 的所有操作外,还支持:

  • order_of_key(x):统计集合中严格小于 x 的元素数量。
  • find_by_order(k):与 find 类似,返回集合中第 k 小元素对应的迭代器(下标从零开始)。

顺序统计树

幸运的是,C++ 已经有这样的内置数据结构。不过它只受 GCC 支持,Clang 用户无法使用。

Resources
CF
CPH

简要介绍 find_by_order 和 order_of_key

KACTL

代码

使用树状数组

不过,如果所有更新都在 [1,N][1,N] 范围内,也可以用树状数组完成相同操作。

Resources
CF

对数级复杂度

使用线段树

这会在铂金组中讲解。

逆序对计数

重点例题 – 继续学习之前,请先尽力独立解决这道题!

实现

Code Snippet: BIT (Click to expand)
MAX_ELEM = 10**7
test_num = int(input())
for _ in range(test_num):
bit = BIT(MAX_ELEM + 1)
input()
arr_len = int(input())

题目

坐标压缩

如果坐标很大(例如达到 10910^9),应在使用树状数组或线段树前进行 坐标压缩 (不过也存在动态开点线段树)。

一般题目

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsPURS
KattisEasy
Show TagsInversions, PURS
CSESEasy
Show TagsPURS
CSESEasy
Show TagsCoordinate Compression, PURS
CFEasy
Show TagsBinary Search, Offline, PURS
CSESEasy
Show TagsCoordinate Compression, PURS
CSESMedium
Show TagsOffline, PURS
CSESHard
Show TagsInversions, PURS

USACO

StatusSourceProblem NameDifficultyTags
GoldEasy
Show TagsInversions, PURS
GoldEasy
Show TagsInversions, PURS
GoldEasy
Show TagsInversions, PURS
GoldEasy
Show TagsPURS
PlatinumEasy
Show TagsInversions, PURS
Old GoldHard
Show TagsPURS

Module Progress:

PrevNext