跳到正文

个人记录

字典树

WSY0814约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年5月26日
收录
2026年5月26日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

没学过树就别看

字典树 其实就是 树的扩展,

给树的每个边起个名字,他就变成了字典树。

如图:

trie

我们举几个例子,我们给 连接 1 和 2 的边 起名为 a,

给 连接 1 和 3 的边 起名为 b,

给 连接 1 和 4 的边 起名为 c。

树上两个节点,不经过重复的边,只有一条路径。

pp 为 Trie 上的某个节点。

从根节点到 pp 的路径是唯一的,

把路径的名字连在一起,就是 pp 表示的状态。

例如 p=12p = 12

从 根节点到 pp 的路径是 [1→4→8→12][1 → 4 → 8 → 12]。

[1→4→8→12][1 → 4 → 8 → 12] 共三条边,分别为 [1→4,4→8,8→12][1 → 4, 4 → 8, 8 → 12],名字分别为 [c,a,a][\text c, \text a, \text a]。

所以 1212 表示的状态就是 caa\text {caa}


那字典树有什么作用呢?

每个节点表示一个 唯一(要求无重边) 的状态,

所以它可以用来表示字符串、维护异或极值、维护异或和。


接下来我们看一下 P2580 的具体实现

C++
struct node {
  int g [26], b;
  node () = default;
} a [1000006];
int tot;

第二行中的 g [26] 是用 邻接列表存储,

第三行 b 表示节点状态(一般为是否模式串结尾)。

C++
int insert (string s)
{
  int j = 0;
  for (const char & c : s)
  {
    int & to = a [j].g [To (c)];
    j = (to ? to : to = ++ tot);
  }
  a [j].b = 1;
  return j;
}
C++
int To (char c)
{
  return c - 'a';
}

To (c) 就是把字符 c 变成整数索引。

j 是当前节点,to 是从 j 连 To (c) 的边。

to ? to : to = ++ tot 表示如果 to 不存在,就建一个新的点,把 to 设为那个点。

最后把 j 移动到 to。

C++
int query (string s)
{
  int j = 0;
  for (const char & c : s)
  {
    int & to = a [j].g [To (c)];
    if (! to) return - 1;
    j = to;
  }
  int ans = a [j].b - 1;
  if (a [j].b != - 1) a [j].b = 2;
  return ans;
}

不断把 s 喂给字典树。

如果在中间没有跳成功,就返回 −1-1 (失败)

如果最后发现不是 某个名字 的结尾,依旧返回 −1-1。

如果是第一次访问,返回 00。

如果不是第一次访问,返回 11。

在主函数输入,插入,最后在每一次访问时查询并判断类型。

完整实现
C++
#include <iostream>
using namespace std;
class Trie
{
		struct node {
			int g [26], b;
			node () = default;
		} a [1000006];
		int tot;
		int To (char c)
		{
			return c - 'a';
		}
public :
		Trie (void) : tot (0) {
            ;
		}
		void clear ()
		{
			for (int i = 0; i <= tot; ++ i)
			{
				a [i].b = 0;
				for (int j = 0; j < 26; ++ j) a [i].g [j] = 0;
			}
		}
		int insert (string s)
		{
			int j = 0;
			for (const char & c : s)
			{
				int & to = a [j].g [To (c)];
				j = (to ? to : to = ++ tot);
			}
            a [j].b = 1;
			return j;
		}
		int query (string s)
		{
			int j = 0;
			for (const char & c : s)
			{
				int & to = a [j].g [To (c)];
				if (! to) return - 1;
                j = to;
            }
            int ans = a [j].b - 1;
            if (a [j].b != - 1) a [j].b = 2;
			return ans;
		}
}T;
string name;
int n;
signed main ()
{
    cin >> n;
    for (int i = 0; i < n; ++ i) cin >> name, T.insert (name);
    cin >> n;
    for (int op, i = 0; i < n; ++ i)
    {
        cin >> name;
        op = T.query (name);
        if (op == - 1) puts ("WRONG");
        else if (! op) puts ("OK");
        else puts ("REPEAT");
    }
    return 0;
}
原文