关于 Trie

· · 个人记录

【Trie 是什么】

Trie,字典树,存储字符串的树形结构。

【Trie 的作用】

Trie 可以高效地查询一个字符串出现的次数。

【Trie 的实现】

Trie 包含:

  1. 布尔数组 tr,其中 tr[i][j]=true 表示 i 号结点有 j 号字符的儿子。

  2. 数组 cnt,cnt[i] 记录 以 i 号结点结尾的字符串个数。

初始只有一个根节点。

每插入一个字符串,都把它的字符遍历一遍。

当遍历到字符 s_i 时,看看当前结点 u 是否有 s_i 这个儿子。

若有,i 后移一位,u 变为这个儿子;

否则给 u 新建一个儿子表示 s_i,再切换到这个儿子上。

遍历结束后,给最后结点的 cnt 值加一。

查询进行类似操作,每次看看当前结点有没有对应字符的儿子。

若有,切换到这个儿子上;

若没有,说明没有这个字符串。

遍历结束后,返回当前结点的 cnt 值。

显然时间复杂度是 O(层数)。

【Code】

板子题:P2580 于是他错误的点名开始了

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

int n;
char s[60];

int tot = 0;
int tr[1000005][50];
int ed[1000005] = {};
int fnd[1000005] = {};

void add(char *s) {
    int len = strlen(s);
    int u = 1;
    for (int i = 0; i < len; i++) {
        int c = s[i] - 'a';
        if (!tr[u][c])
            tr[u][c] = ++tot;
        u = tr[u][c];
    }
    ed[u]++;    
}

int query(char *s) {
    int len = strlen(s), u = 1;
    for (int i = 0; i < len; i++) {
        int c = s[i] - 'a';
        if (tr[u][c] == 0)
            return 0;
        u = tr[u][c];
    }
    if (fnd[u])
        return 1;
    fnd[u]++;
    return 2;
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        scanf("%s", &s);
        add(s);
    }
    int m;
    cin >> m;
    for (int i = 1; i <= m; i++) {
        scanf("%s", s);
        int tmp = query(s);
        if (tmp == 0)
            cout << "WRONG" << endl;
        else if (tmp == 1)
            cout << "REPEAT" << endl;
        else
            cout << "OK" << endl;
    }
    return 0;
}