字典树

· · 个人记录

没学过树就别看

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

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

如图:

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

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

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

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

从根节点到 $p$ 的路径是唯一的, 把路径的名字连在一起,就是 $p$ 表示的状态。 例如 $p = 12

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

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

那字典树有什么作用呢?

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

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

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

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

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

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

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 To (char c)
{
  return c - 'a';
}

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

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

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

最后把 j 移动到 to。

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。

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

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

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

::::info[完整实现]

#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;
}

::::