跳到正文

算法·理论

向量化线段树

masonxiong约 13 分钟
原文
文章信息与版本

文章信息

发布
2026年10月21日
收录
2026年10月24日
更新
2026年11月11日
篇幅
约 13 分钟
获赞
60

版本

  1. v1当前

省流:单点加,前缀和,树状数组两倍速度。

核心原理

将下标 ii 拆成 ww 进制 i=∑k=0h−1ik⋅wki=\sum_{k=0}^{h-1}i_k\cdot w^k,相当于把区间 [0,i)[0,i) 拆成 iki_k 个长度为 wkw^k 的区间。考虑一棵 ww 叉线段树,自下向上第 kk 层的节点管辖长度为 wk⋅ww^k\cdot w 的区间,节点上有一个长度为 ww 的序列 s(k)s(k),其中 s(k)is(k)_i 表示:这个长度为 wk⋅ww^k\cdot w 的区间中,前 ii 个长度为 wkw^k 的小区间的所有元素之和。根据定义有 s(k)0=0s(k)_0=0。

将第 kk 层内所有节点的 s(k)s(k) 序列从左到右拼接,得到这一层的序列 S(k)\mathrm S(k)。它的下标是层内下标,不是原序列下标:原下标 ii 落在 S(k)⌊i⋅w−k⌋\mathrm S(k)_{\lfloor i\cdot w^{-k}\rfloor}。

设 j=⌊i⋅w−k⌋j=\lfloor i\cdot w^{-k}\rfloor,则 S(k)j\mathrm S(k)_j 是所有满足下列条件的 axa_x 之和:把 xx 与 ii 写成 ww 进制后,高于第 kk 位的各位与 ii 相同,第 kk 位严格小于 ii 的第 kk 位,更低位任意。

下面是一个 w=4,n=16w=4,n=16 的例子,最下一行为原序列 aa:

代码
[00,             10,             36,             78            ] S(1)
[00, 01, 03, 06, 00, 05, 11, 18, 00, 09, 19, 30, 00, 13, 27, 42] S(0)
[01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16] a

查询 ∑[0,i)\sum[0,i) 就是求 ∑x<iax\sum\limits_{x<i} a_x。每个 x<ix<i 都有唯一的最高位 kk,使得 xx 与 ii 在高于 kk 的各位上相同,而 xx 的第 kk 位严格更小,更低位任意。

这些 xx 的 axa_x 之和就是 S(k)⌊i⋅w−k⌋\mathrm S(k)_{\lfloor i\cdot w^{-k}\rfloor}。kk 取遍 [0,h)[0,h) 时,这些集合互不相交,并且覆盖全部 x<ix<i,所以 [0,i)[0,i) 的和为:

∑k=0h−1S(k)⌊i⋅w−k⌋\sum_{k=0}^{h-1}\mathrm S(k)_{\lfloor i\cdot w^{-k}\rfloor}

例如 i=6=(12)4i=6=(12)_4,则 ∑[0,6)=S(0)6+S(1)⌊6⋅4−1⌋=11+10=21\sum[0,6)=\mathrm S(0)_6+\mathrm S(1)_{\lfloor 6\cdot 4^{-1}\rfloor}=11+10=21。于是求和的时间复杂度为 O(h)=O(log⁡wn)\mathcal O(h)=\mathcal O(\log_wn)。

接下来考虑修改 ai←+da_i\xleftarrow+d。第 kk 层的 S(k)j\mathrm S(k)_j 含有 aia_i,当且仅当 jj 与 ⌊i⋅w−k⌋\lfloor i\cdot w^{-k}\rfloor 位于同一个节点,且 j mod w>ikj\bmod w>i_k。因此每一层只有一个节点会被改到:令 j=⌊i⋅w−k⌋j=\lfloor i\cdot w^{-k}\rfloor,节点起点为 j−ikj-i_k,对节点内下标 v∈(ik,w)v\in(i_k,w) 执行 S(k)j−ik+v←+d\mathrm S(k)_{j-i_k+v}\xleftarrow+d 即可。于是修改的时间复杂度为 O(wh)=O(wlog⁡wn)\mathcal O(wh)=\mathcal O(w\log_wn)。

注意到修改操作中每一层的修改形如”将连续 ww 个元素进行增加”,这启发我们进行向量化。预处理掩码 mu,v=−[u<v]m_{u,v}=-[u<v],将 dd 广播之后与 mikm_{i_k} 按位与再加到节点上即可。

接下来考虑 ww 的选取。假设我们维护的是 3232 位整数,使用 AVX2 指令集的 256256 位向量,为了方便进行向量化,首先应当有 8∣w8\mid w。同时内存读取时总会以缓存行为最小单位进行取出,缓存行的大小为 6464 字节,那我们刚好可以取 w=16w=16,这样一个节点刚好为一个缓存行,同时修改操作可以拆成两次指令。

下面的代码给出一个示例,实现了 00-indexed 单点加,求左闭右开前缀和。冷知识:下面这个代码不依赖头文件。

示例代码
C++
template <int N>
class WideSGT {
    using Vector = int __attribute__((vector_size(32)));

    static constexpr int Cacheline = 64;
    static constexpr int Block = Cacheline / sizeof(int);
    static constexpr int Width = __builtin_ctz(Block);

    struct Mask {
        alignas(Cacheline) int mask[Block][Block];

        constexpr Mask() : mask{} {
            for (int u = 0; u < Block; ++u)
                for (int v = 0; v < Block; ++v)
                    mask[u][v] = u < v ? -1 : 0;
        }
    };

    static constexpr int height(int i) {
        int result = 1, n = i;
        while (n >= Block) {
            n >>= Width;
            ++result;
        }
        return result;
    }

    static constexpr int offset(int i) {
        int result = 0, n = N;
        while (i--) {
            n = (n + ~-Block) / Block;
            result += n * Block;
        }
        return result;
    }

    static constexpr int Size = N;
    static constexpr int Height = height(Size);

    alignas(Cacheline) int data[static_cast<unsigned>(offset(Height))];
    static constexpr Mask mask{};

public:
    int sum(int position) {
        int result = 0;
        for (int i = 0; i < Height; ++i) {
            result += data[offset(i) + position];
            position >>= Width;
        }
        return result;
    }

    void modify(int position, int delta) {
        auto vector = Vector{} + delta;
        for (int i = 0; i < Height; ++i) {
            auto block = (Vector*)&data[offset(i) + (position & -Block)];
            auto vmask = (Vector*)&mask.mask[position & ~-Block];
            block[0] += vector & vmask[0];
            block[1] += vector & vmask[1];
            position >>= Width;
        }
    }
};

效率测试

  • 评测机:Intel(R) Core(TM) Ultra 9 285H
  • 编译器:g++ (x86_64-win32-seh-rev0, Built by MinGW-Builds project) 15.2.0
  • 编译参数:-std=c++23 -march=native -mtune=native -Ofast

序列长度 n=107n=10^7,2⋅1072\cdot 10^7 次随机下标修改,2⋅1072\cdot 10^7 次随机下标求和。1010 次测试平均。

  • WideSGT:1162.4 ms1162.4\space\rm ms
  • Fenwick:2052.3 ms2052.3\space\rm ms

两倍速度。伟大无需多言。

测试代码
C++
template <int N>
class WideSGT {
    using Vector = int __attribute__((vector_size(32)));

    static constexpr int Cacheline = 64;
    static constexpr int Block = Cacheline / sizeof(int);
    static constexpr int Width = __builtin_ctz(Block);

    struct Mask {
        alignas(Cacheline) int mask[Block][Block];

        constexpr Mask() : mask{} {
            for (int u = 0; u < Block; ++u)
                for (int v = 0; v < Block; ++v)
                    mask[u][v] = u < v ? -1 : 0;
        }
    };

    static constexpr int height(int i) {
        int result = 1, n = i;
        while (n >= Block) {
            n >>= Width;
            ++result;
        }
        return result;
    }

    static constexpr int offset(int i) {
        int result = 0, n = N;
        while (i--) {
            n = (n + ~-Block) / Block;
            result += n * Block;
        }
        return result;
    }

    static constexpr int Size = N;
    static constexpr int Height = height(Size);

    alignas(Cacheline) int data[static_cast<unsigned>(offset(Height))];
    static constexpr Mask mask{};

public:
    int sum(int position) {
        int result = 0;
        for (int i = 0; i < Height; ++i) {
            result += data[offset(i) + position];
            position >>= Width;
        }
        return result;
    }

    void modify(int position, int delta) {
        auto vector = Vector{} + delta;
        for (int i = 0; i < Height; ++i) {
            auto block = (Vector*)&data[offset(i) + (position & -Block)];
            auto vmask = (Vector*)&mask.mask[position & ~-Block];
            block[0] += vector & vmask[0];
            block[1] += vector & vmask[1];
            position >>= Width;
        }
    }
};

template <int N>
class Fenwick {
    int data[static_cast<unsigned>(N)];

public:
    int sum(int position) {
        int result = 0;
        while (position--) {
            result += data[position];
            position &= -~position;
        }
        return result;
    }

    void modify(int position, int delta) {
        while (position < N) {
            data[position] += delta;
            position |= -~position;
        }
    }
};

#include <ctime>
#include <random>
#include <iostream>

auto main() -> int {
    static constexpr int N = 1E7;
    static constexpr int M = 2E7;
    static WideSGT<N> tree;

    int xorsum = 0;
    std::mt19937 rng;
    for (int i = M; i--; ) {
        tree.modify(rng() % N, 1);
        xorsum ^= i ^ tree.sum(rng() % N);
    }

    std::cerr << "XorSum = " << xorsum << '\n';
    std::cout << "Duration = " << std::clock() << " clocks\n";
}
原文
存档评论31 条抓取于