值域树状数组

· · 个人记录

:::epigraph[——某位被离散化折磨过的 OIer] "值域树状数组?不就是普通树状数组把下标从位置换成数值吗……等等,离散化怎么又出锅了?" :::

前置知识

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

① 叫什么

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

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

② 地位

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

③ 用途

④ 核心原理

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

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

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

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

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

⑤ 具体原理

5.1 离散化:把值变成下标

假设原始数组:

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

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

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

Step 2:映射回原数组

位置 i 1 2 3 4 5
a_i \color{blue}{7} \color{green}{3} \color{red}{9} \color{green}{3} \color{purple}{11}
排名 rk_i \color{blue}{2} \color{green}{1} \color{red}{3} \color{green}{1} \color{purple}{4}

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

5.2 值域 BIT 的结构

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

tr_4 < < < <
tr_2 < <
tr_1 tr_3

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

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

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

初始状态:值域 BIT 全空

tr_4 < < < <
tr_2 < <
tr_1

扫描过程:

步骤 位置 原始值 排名 查询:排名 < rk 的个数 逆序对增量 操作:add(rk, 1)
1 5 11 4 sum(4-1) = 0 +0 tr_4 += 1
2 4 3 1 sum(1-1) = 0 +0 tr_1 += 1
3 3 9 3 sum(3-1) = 1 +1 tr_3 += 1
4 2 3 1 sum(1-1) = 0 +0 tr_1 += 1(此时 tr_1=2)
5 1 7 2 sum(2-1) = 2 +2 tr_2 += 1
\text{总逆序对} = 0+0+1+0+2 = \boxed{3}

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

5.4 第 k 大查询:在 BIT 上"按位跳"

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

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

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

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

那就把 KaTeX 当成画布来画。

核心等式

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

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

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

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

\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 的下标直接是值本身(或离散化后的排名):

\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 \text{lowbit} 的「管辖范围」可视化

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

\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}
\textcolor{purple}{tr_8} < < < < < < <
\textcolor{blue}{tr_4} < < < < < <
\textcolor{teal}{tr_2} < < \textcolor{teal}{tr_6} < <
\textcolor{red}{tr_1} \textcolor{red}{tr_3} \textcolor{red}{tr_5} \textcolor{red}{tr_7}

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

6 \xrightarrow{-\text{lowbit}(6)=2} 4 \xrightarrow{-\text{lowbit}(4)=4} 0

即:

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

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

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

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

严格写:

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

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

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

插入一个值 x,映射到排名 p:

\boxed{ p \xrightarrow{+\text{lowbit}} p+\text{lowbit}(p) \xrightarrow{+\text{lowbit}} \cdots \le m }

公式步:

\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 第 k 小:在树状数组上二分

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

\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:

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

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

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

\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 的 i 问的是「第 i 个元素的前缀和是多少」;
值域 BIT 的 i 问的是「值不超过 i 的数出现了多少次」。
把「位置轴」旋转 90^\circ 变成「值轴」,就是值域树状数组。

完整代码

::::info[值域树状数组模板(支持离散化 + 逆序对 + 第 k 大)]{open}

#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;  // 完结散花!
}

::::

复杂度总览

::cute-table{tuack}

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

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