gwl999

博客园 首页 新随笔 联系 订阅 管理

5.19

Trie树:

  • 用处:快速的查找和高效存储字符串集合的数据结构。

  •  

     

  • 类似如此的查找,存储

  • 其简单的两个操作:插入和删除

  • 插入:

    • void insert(char str[]) {
          int p;
          //定义数据前一位的位置
          for (int i = 0; i < str[i]; i++) {
              int u = str[i] - 'a';
              //初始化映射
              if (!son[p][u])
                  //如果找不到上一个结点
                  son[p][u] = ++idx;
              //那么就去创建一个结点
              p = son[p][u];
              //每次遍历向下,并且它的上一个是idx指针
          }
          cnt[p]++;
          //结束时的标记,也是记录以此节点结束的字符串个数
      }
  • 删除

    • int query(char str[]) {
          int p;
          for (int i = 0; i < str[i]; i++) {
              int u = str[i] - 'a';
              if (!son[p][u])
                  return 0;
              p = son[p][u];
              //直接每次遍历向下
          }
          return cnt[p];
      }

例题:https://www.acwing.com/problem/content/837/


#include "iostream"
using namespace std;
const int N = 100010;
int son[N][26], cnt[N], idx;
void insert(char str[]) {
    int p;
    for (int i = 0; i < str[i]; i++) {
        int u = str[i] - 'a';
        if (!son[p][u])
            son[p][u] = ++idx;
        p = son[p][u];
    }
    cnt[p]++;
}
int query(char str[]) {
    int p;
    for (int i = 0; i < str[i]; i++) {
        int u = str[i] - 'a';
        if (!son[p][u])
            return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main() {
    int m;
    cin >> m;
    char str[N];
    while (m--) {
        char s;
        cin >> s;
        if (s == 'I') {
            cin >> str;
            insert(str);
        } else if (s == 'Q') {
            cin >> str;
            cout << query(str) << endl;
        }
    }
    return 0;
}

解释图片:

 

 

图片来源:AcWing 835. Trie字符串统计 - AcWing

posted on 2022-05-19 23:13  呓雫  阅读(35)  评论(0)    收藏  举报