跳到正文

算法·理论

字典树学习笔记

#SUSPENDED#约 11 分钟
原文
文章信息与版本

文章信息

发布
2026年2月10日
收录
2026年4月27日
更新
2026年11月10日
篇幅
约 11 分钟

版本

  1. v2当前
  2. v1

何为字典树

字典树,英文名Trie。顾名思义,像字典一样的树。

是一种树形结构,典型应用是用于统计、排序与保存大量字符串(不仅限于字符串。如01字典树)。

先放一张OIWiki上偷的图: 字典树

这棵树用边来存每个字母,从根节点到叶子节点走一遍,就相当于是一个字符串。

例如从1∼4∼8∼12∼151\sim4\sim8\sim12\sim15,代表的字符串就是:caaa。

字典树比暴力存储的关键优化:利用字符串间的公共前缀来一树的形式存储单词,大大压缩内存、提高查询效率。

如何实现

字典树的操作主要只有两种:插入与查找。

这次例题是P8306。嗯,就是这俩操作。

插入

先画图,在图上模拟插入的过程:

代码
                  根节点
                    |
                    c (children[2])
                    |
                    a (children[0])
                    |
                    t (children[19])
                    ↓
                  根节点
                    |
                    c (children[2])
                    |
                    a (children[0])
                   / \
                r/    \t
               /       \
                  ↓插入了一堆
                根节点
               /      \
              c        d
             /        / \
            a        o   o
           / \      /     \
          r   t    g*      n*
                  /         \
                 e*          e*

从图上看清楚了,插入的步骤就是:

  1. 把字符串拆成单个字符。
  2. 从前往后的开始与当前树的根节点开始的子节点对比。
  3. 若和当前节点相同,则接着往下比对。否的要开新节点。
  4. 最后,记得给叶子节点打结束标记,防止某些猎奇的事情发生。 接下来就可以写代码了。首先,定义二维数组trie表示树结构,第二维要开到63(因为有大小字母、数字)。这个数组存的是每个节点的子节点。

此外,还要一个cnt数组,记录以这个字母结尾的单词有几个。(即结束标记)。

还要一个tot来存节点个数,每使用到一个新节点,就让他自增并映射到该节点上去。

C++
const int N = 3e6 + 10;
const int M = 63;
int trie[N][M], cnt[N], tot;
int get(char x) {
    if (x >= 'A' && x <= 'Z') {
        return x - 'A';
    }
    else if (x >= 'a' && x <= 'z') {
        return x - 'a' + 26;
    }
    else {
        return x - '0' + 52;
    }
}//字符转为整数
void ins(string s) {
    int x = 0,/*遍历的索引*/ n = s.size();
    for (int i = 0; i < n; ++i) {
        int v = get(s[i]);//分离字符
        if (!trie[x][v]) {//未创建
            trie[x][v] = ++tot;//创建新节点
        }
        x = trie[x][v];//指向子节点
        cnt[x]++;//结束标记
    }
}

查找

和插入差不多(图太占空间,不画了)。

  1. 分离字符。
  2. 一个个和trie树比较。
  3. 直至发现树中不存在的字符,或者找完了(找到了)。 插入、查找都是O(∣s∣)O(|s|)的。
C++
int fnd(string s) {
    int x = 0, n = s.size();
    for (int i = 0; i < n; ++i) {
        int v = get(s[i]);
        if (!trie[x][v]) {
            return 0;//不存在
        }
        x = trie[x][v];//都差不多
    }
    return cnt[x];//返回街尾节点的单词计数
}

于是,这题就做完了。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e6 + 10;
const int M = 63;
int trie[N][M], cnt[N], tot;
int get(char x) {
    if (x >= 'A' && x <= 'Z') {
        return x - 'A';
    }
    else if (x >= 'a' && x <= 'z') {
        return x - 'a' + 26;
    }
    else {
        return x - '0' + 52;
    }
}
void ins(string s) {
    int x = 0, n = s.size();
    for (int i = 0; i < n; ++i) {
        int v = get(s[i]);
        if (!trie[x][v]) {
            trie[x][v] = ++tot;
        }
        x = trie[x][v];
        cnt[x]++;
    }
}
int fnd(string s) {
    int x = 0, n = s.size();
    for (int i = 0; i < n; ++i) {
        int v = get(s[i]);
        if (!trie[x][v]) {
            return 0;
        }
        x = trie[x][v];
    }
    return cnt[x];
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    for (cin >> T; T; --T) {
        int n, q;
        cin >> n >> q;
        for (int i = 0; i <= tot; ++i) {
            memset(trie[i], 0, sizeof trie[i]);
            cnt[i] = 0;
        }
        tot = 0;
        for (int i = 1; i <= n; ++i) {
            string s;
            cin >> s;
            ins(s);
        }
        while (q--) {
            string s;
            cin >> s;
            cout << fnd(s) << '\n';
        }
    }
    return 0;
}

拓展0/1字典树

一个问题:求一个数组中子数组的最大异或和

虽然看着和字典树毫无关系,但可以用0/1字典树维护该问题。

可以把每个是转化成二进制,然后就能像字符串一样,把他们丢进字典树里存起来。

当然,要先用前缀异或,方便求区间异或值。

对于trie树,我们采取贪心: 要使 xyx ^ y 最大,应让高位尽可能为 1

对于第 kk 位:

如果 xx 的第 kk 位是 11,我们希望在 yy中找第 kk 位是 00 的数

如果 xx 的第 kk 位是 00,我们希望找第 kk 位是 11 的数

所以代码不难:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 2e5 + 10;
int trie[N * 32][2];
int n, tot, ans = 0;

void ins(int v) {
    int x = 0;
    for (int i = (1 << 30); i; i >>= 1) {
        int a = bool(v & i);
        if (!trie[x][a]) {
            trie[x][a] = ++tot;
        }
        x = trie[x][a];
    }
}

int fnd(int v) {
    int res = 0, x = 0;
    for (int i = (1 << 30); i; i >>= 1) {
        int a = bool(v & i);
        if (trie[x][!a]) {
            res += i;
            x = trie[x][!a];
        } else {
            x = trie[x][a];
        }
    }
    return res;
}//01字典树
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;
    vector<int> a(n + 1);
    vector<int> pre_xor(n + 1, 0);
    tot = 0;
    memset(trie, 0, sizeof(trie));
    ins(0);
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
        pre_xor[i] = pre_xor[i - 1] ^ a[i];
        ans = max(ans, fnd(pre_xor[i]));
        ins(pre_xor[i]);//插入
    }
    ans = max(ans, pre_xor[n] ^ 0);  //查找
    cout << ans << '\n';
    return 0;
}

练习题锦集

字典树-黄

字典树-绿

字典树-蓝

原文