跳到正文

个人记录

值域树状数组

djhcbhgs44约 19 分钟
原文
文章信息与版本

文章信息

发布
2026年8月9日
收录
2026年8月9日
更新
2026年11月17日
篇幅
约 19 分钟

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1

“值域树状数组?不就是普通树状数组把下标从位置换成数值吗……等等,离散化怎么又出锅了?”

——某位被离散化折磨过的 OIer

前置知识

建议先阅读 树状数组基础(打不开点我),理解 lowbit、add、sum 的跳步原理。本文在此基础上,把下标的含义从”位置”换成”数值排名”。


① 叫什么

值域树状数组(Fenwick Tree on Value Domain),也叫权值树状数组。

普通树状数组的下标是序列位置 (1,2,…,n)(1,2,\dots,n),值域树状数组的下标是数值的排名 (1,2,…,m)(1,2,\dots,m)。


② 地位

动态维护”数值分布”的最轻量级数据结构。线段树能做,但树状数组常数更小、代码更短。它是逆序对、动态第 kk 大的标准起手式。


③ 用途

  • 逆序对:从右往左扫,查”右边有多少个比我小的”
  • 动态第 kk 大 / 第 kk 小:利用前缀和的单调性在 BIT 上按位跳
  • 在线计数排序:支持插入、删除(单点修改)和前缀次数查询

④ 核心原理

普通 BIT 维护的是位置前缀和:

sum(i)=∑j=1iaj\text{sum}(i) = \sum_{j=1}^{i} a_j

值域 BIT 维护的是值域前缀次数:

cnt(r)=∑排名≤r出现次数\text{cnt}(r) = \sum_{\text{排名} \le r} \text{出现次数}

关键桥梁是离散化——把巨大的值域压缩成紧凑的排名。


⑤ 具体原理

5.1 离散化:把值变成下标

假设原始数组:

a=[7, 3, 9, 3, 11]a = [7,\ 3,\ 9,\ 3,\ 11]

Step 1:去重排序,建立映射

原始值3\color{green}{3}7\color{blue}{7}9\color{red}{9}11\color{purple}{11}
排名1\color{green}{1}2\color{blue}{2}3\color{red}{3}4\color{purple}{4}

Step 2:映射回原数组

位置 ii12345
aia_i7\color{blue}{7}3\color{green}{3}9\color{red}{9}3\color{green}{3}11\color{purple}{11}
排名 rkirk_i2\color{blue}{2}1\color{green}{1}3\color{red}{3}1\color{green}{1}4\color{purple}{4}

现在值域 BIT 只需要开 m=4m=4 个节点,而不是开到 1111。


5.2 值域 BIT 的结构

把排名当作下标,结构与普通 BIT 完全一样,只是语义变了:

tr4tr_4
tr2tr_2
tr1tr_1tr3tr_3

但这里的 tritr_i 不再表示”位置区间和”,而是表示**“排名区间内的出现次数”**:

  • tr1tr_1:排名 11 的出现次数
  • tr2tr_2:排名 1∼21\sim2 的出现次数
  • tr3tr_3:排名 33 的出现次数
  • tr4tr_4:排名 1∼41\sim4 的出现次数

5.3 逆序对:值域 BIT 的经典首秀

核心思想:从右往左扫描,每次查询”已经处理过的元素里,值比我小的有多少个”。

初始状态:值域 BIT 全空

tr4tr_4
tr2tr_2
tr1tr_1

扫描过程:

步骤位置原始值排名查询:排名 <rk< rk 的个数逆序对增量操作:add(rk, 1)
1155111144sum(4-1) = 0+0+0tr4tr_4 += 1
22443311sum(1-1) = 0+0+0tr1tr_1 += 1
33339933sum(3-1) = 1+1+1tr3tr_3 += 1
44223311sum(1-1) = 0+0+0tr1tr_1 += 1(此时 tr1=2tr_1=2)
55117722sum(2-1) = 2+2+2tr2tr_2 += 1
总逆序对=0+0+1+0+2=3\text{总逆序对} = 0+0+1+0+2 = \boxed{3}

验证:(1,2):7>3(1,2): 7>3,(1,4):7>3(1,4): 7>3,(3,4):9>3(3,4): 9>3,共 3 对。✓


5.4 第 kk 大查询:在 BIT 上”按位跳”

值域 BIT 的前缀和数组是单调不降的,因此可以 O(log⁡m)O(\log m) 定位”前缀和首次 ≥k\ge k 的位置”。

核心思想:利用 BIT 的二进制分层结构,从高位到低位试探。

假设 m=8m=8,各节点存储的次数如下(前缀和数组为 [1,1,2,4,4,4,5,6][1,1,2,4,4,4,5,6]),找第 44 小:

当前位试探位置前缀和是否 ≥4\ge 4决策
40 + 4 = 4sum(4) = 4✓ ≥4\ge 4不跳,保留 0
20 + 2 = 2sum(2) = 1✗ <4< 4跳!pos = 2, k -= 1
12 + 1 = 3sum(3) = 2✗ <4< 4跳!pos = 3, k -= 2
结束3 + 1 = 4——答案 = 4

那就把 KaTeX 当成画布来画。


核心等式

值域 BIT 的全部秘密,可以框进这一行:

ans(x)=∑v≤xcv⟺query(rank(x))\boxed{ \text{ans}(x) = \sum_{\substack{v \le x}} c_v \quad \Longleftrightarrow \quad \text{query}\Bigl(\text{rank}(x)\Bigr) }

6.1 下标不是位置,是「值」

普通 BIT 的下标是数组下标:

下标 i12345678ai53714268\begin{array}{|c|c|c|c|c|c|c|c|} \hline \text{下标 } i & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ \hline a_i & 5 & 3 & 7 & 1 & 4 & 2 & 6 & 8 \\ \hline \end{array}

值域 BIT 的下标直接是值本身(或离散化后的排名):

值 v12345678cv (出现次数)11111111tree[v]12141218\begin{array}{|c|c|c|c|c|c|c|c|c|} \hline \text{值 } v & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ \hline c_v\ (\text{出现次数}) & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ \hline \color{blue} \text{tree}[v] & 1 & 2 & 1 & 4 & 1 & 2 & 1 & 8 \\ \hline \end{array}

同一行数字,意义完全不同。左边是位置序列,右边是统计直方图。


6.2 lowbit\text{lowbit} 的「管辖范围」可视化

每个节点 ii 管辖一段长度为 lowbit(i)\text{lowbit}(i) 的区间。用彩色块标出来:

i12345678lowbit(i)12141218管辖区间[1,1][1,2][3,3][1,4][5,5][5,6][7,7][1,8]\begin{array}{c|cccccccc} i & \textcolor{red}{1} & \textcolor{teal}{2} & \textcolor{red}{3} & \textcolor{blue}{4} & \textcolor{red}{5} & \textcolor{teal}{6} & \textcolor{red}{7} & \textcolor{purple}{8} \\ \hline \text{lowbit}(i) & 1 & 2 & 1 & 4 & 1 & 2 & 1 & 8 \\ \hline \text{管辖区间} & [1,1] & [1,2] & [3,3] & [1,4] & [5,5] & [5,6] & [7,7] & [1,8] \\ \end{array}
tr8\textcolor{purple}{tr_8}
tr4\textcolor{blue}{tr_4}
tr2\textcolor{teal}{tr_2}tr6\textcolor{teal}{tr_6}
tr1\textcolor{red}{tr_1}tr3\textcolor{red}{tr_3}tr5\textcolor{red}{tr_5}tr7\textcolor{red}{tr_7}

用箭头画一次前缀查询 query(6)\text{query}(6) 的跳跃路径:

6→−lowbit(6)=24→−lowbit(4)=406 \xrightarrow{-\text{lowbit}(6)=2} 4 \xrightarrow{-\text{lowbit}(4)=4} 0

即:

query(6)=tree[6]⏟[5,6]+tree[4]⏟[1,4]=∑v=16cv\text{query}(6) = \underbrace{\text{tree}[6]}_{[5,6]} + \underbrace{\text{tree}[4]}_{[1,4]} = \sum_{v=1}^{6} c_v

6.3 离散化:把宇宙压进一个数组

原始值域炸到 10910^9 没关系,只需要保序压缩:

原始值→排序去重排名{42, 109, 7, 42, 999}⟹{2, 4, 1, 2, 3}\begin{array}{ccc} \text{原始值} & \xrightarrow{\text{排序去重}} & \text{排名} \\ \{ 42,\ 10^9,\ 7,\ 42,\ 999 \} & \Longrightarrow & \{ 2,\ 4,\ 1,\ 2,\ 3 \} \\ \end{array}

严格写:

rank(x)=∣{y∈S ∣ y≤x}∣,S=sorted_unique({ai})\text{rank}(x) = \left| \Bigl\{ y \in S \,\Big|\, y \le x \Bigr\} \right|, \quad S = \text{sorted\_unique}(\{a_i\})

此后 BIT 只开到 ∣S∣|S|,所有操作在排名空间 [1,∣S∣][1, |S|] 上进行。


6.4 单点修改:往「值」的位置 +1

插入一个值 xx,映射到排名 pp:

p→+lowbitp+lowbit(p)→+lowbit⋯≤m\boxed{ p \xrightarrow{+\text{lowbit}} p+\text{lowbit}(p) \xrightarrow{+\text{lowbit}} \cdots \le m }

公式步:

add(p, Δ):while p≤m:tree[p]+=Δp+=p & (−p)\begin{aligned} &\text{add}(p,\ \Delta): \\ &\quad \texttt{while } p \le m: \\ &\quad\quad \text{tree}[p] \mathrel{+}= \Delta \\ &\quad\quad p \mathrel{+}= p\ \&\, (-p) \end{aligned}

6.5 第 kk 小:在树状数组上二分

这是值域 BIT 最帅的操作。利用树状数组的分层结构直接跳:

find_kth(k):p←0,step←2⌊log⁡2m⌋while step>0:if p+step≤m and tree[p+step]<k:k−=tree[p+step]p+=stepstep/=2return p+1\boxed{ \begin{aligned} &\text{find\_kth}(k): \\ &\quad p \leftarrow 0,\quad \text{step} \leftarrow 2^{\lfloor \log_2 m \rfloor} \\ &\quad \texttt{while } \text{step} > 0: \\ &\quad\quad \texttt{if } p+\text{step} \le m \ \textcolor{red}{\textbf{and}}\ \text{tree}[p+\text{step}] < k: \\ &\quad\quad\quad k \mathrel{-}= \text{tree}[p+\text{step}] \\ &\quad\quad\quad p \mathrel{+}= \text{step} \\ &\quad\quad \text{step} \mathrel{/}= 2 \\ &\quad \textbf{return } p+1 \end{aligned} }

Python:

Python
def find_kth(k):
  p,step=0,int(log2(m))>>1
  while step>0:
    if p+step<=m and tree[p+step]<k:
      k-=tree[p+step]
      p+=step
    step/=2

原理一句话:从高位到低位试探,如果跳过去之后累计还不够 kk,就跳。


6.6 一张图看懂「值域」vs「普通」

普通 BIT(下标 = 位置)⏟维护 ∑i=1rai值域 BIT(下标 = 值)⏟维护 ∑v≤xcvi123…信息a1a2a3…v123…信息c1c2c3…\begin{array}{cc} \underbrace{\begin{array}{c} \text{普通 BIT} \\ \text{(下标 = 位置)} \end{array}}_{\text{维护 } \sum_{i=1}^{r} a_i} & \qquad\qquad & \underbrace{\begin{array}{c} \text{值域 BIT} \\ \text{(下标 = 值)} \end{array}}_{\text{维护 } \sum_{v \le x} c_v} \\[20pt] \begin{array}{|c|c|c|c|c|} \hline i & 1 & 2 & 3 & \dots \\ \hline \text{信息} & a_1 & a_2 & a_3 & \dots \\ \hline \end{array} & & \begin{array}{|c|c|c|c|c|} \hline v & 1 & 2 & 3 & \dots \\ \hline \text{信息} & c_1 & c_2 & c_3 & \dots \\ \hline \end{array} \end{array}

6.7 一句话

普通 BIT 的 ii 问的是「第 ii 个元素的前缀和是多少」;
值域 BIT 的 ii 问的是「值不超过 ii 的数出现了多少次」。
把「位置轴」旋转 90∘90^\circ 变成「值轴」,就是值域树状数组。


完整代码

值域树状数组模板(支持离散化 + 逆序对 + 第 k 大)
C++
#include <bits/stdc++.h>
using namespace std;

using T = long long;

struct Disc {
    vector<T> a;
    Disc(vector<T> v) { init(v); }
    void init(vector<T> v) {
        sort(v.begin(), v.end());
        v.erase(unique(v.begin(), v.end()), v.end());
        a = v;
    }
    int get(T x) {
        return lower_bound(a.begin(), a.end(), x) - a.begin() + 1;
    }
    int size() { return a.size(); }
};

struct Fenwick {
    int n;
    vector<T> tr;
    Fenwick(int n = 0) { init(n); }
    
    void init(int _n) {
        n = _n;
        tr.assign(n + 1, 0);
    }
    
    void add(int x, T c) {
        for(; x <= n; x += x & -x) tr[x] += c;
    }
    
    T sum(int x) const {
        T res = 0;
        for(; x; x -= x & -x) res += tr[x];
        return res;
    }
    
    // 找第 k 小的排名(1-indexed, k >= 1)
    int kth(T k) const {
        int pos = 0;
        int bit = 1;
        while(bit << 1 <= n) bit <<= 1;
        for(; bit; bit >>= 1) {
            int nxt = pos + bit;
            if(nxt <= n && tr[nxt] < k) {
                k -= tr[nxt];
                pos = nxt;
            }
        }
        return pos + 1;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n;
    cin >> n;
    vector<T> a(n);
    for(T &x : a) cin >> x;
    
    // 离散化
    Disc disc(a);
    Fenwick bit(disc.size());
    
    long long inv = 0;
    
    // 逆序对:从右往左
    for(int i = n - 1; i >= 0; i--) {
        int rk = disc.get(a[i]);
        inv += bit.sum(rk - 1);  // 右边有多少个比我小的
        bit.add(rk, 1);
    }
    
    cout << inv << '\n';
    return 0;  // 完结散花!
}

复杂度总览

操作时间复杂度空间复杂度备注
离散化O(nlog⁡n)O(n \log n)O(n)O(n)排序去重
单点修改O(log⁡m)O(\log m)—mm 为不同值个数
前缀查询O(log⁡m)O(\log m)——
第 kk 大O(log⁡m)O(\log m)—按位跳,非二分
逆序对(整体)O(nlog⁡m)O(n \log m)O(m)O(m)扫描一遍

一句话总结:值域树状数组 = 离散化 + 普通 BIT,把”位置的游戏”变成了”值的游戏”。逆序对只是它的开胃菜,第 kk 大才是正餐。

原文