当前位置:网站首页>Trie思想及模板
Trie思想及模板
2022-08-03 17:14:00 【lcy2023】
参考博文:https://www.acwing.com/solution/content/14695/
课程链接:https://www.acwing.com/video/260/
例题链接:https://www.acwing.com/problem/content/837/
思想
用于高效的存储和查找字符串集合的数据结构,用Trie树的字符串一般要么是小写字母要么都是大写字母,类型不会多,字符串的长度也不会太长
root为空节点,图中五角星的意思是标记有以该字母结尾的字符串,代码表示是cnt数组,记录以该字母结尾的字符串的数量
例题
该题目中都为26个字母,所以可以开辟son[][26]数组,来映射26个字母,该数组表示的是子节点,用son[]某节点的所有子节点,son[]列映射为子节点的值,son[][]的值表示该节点是第几个加入的不重复的节点。cnt[]数组标识字符串的结束,idx用来确定节点是否存在
代码
#include <iostream>
using namespace std;
const int N = 100010;
int son[N][26], cnt[N], idx;
char str[N];
void insert(char *str)
{
int p = 0;
for (int i = 0; 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 = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - 'a';
if (!son[p][u]) return 0;
p = son[p][u];
}
return cnt[p];
}
int main()
{
int n;
scanf("%d", &n);
while (n -- )
{
// 此处设置成op[2],而不是char op,是因为char op用scanf("%c")会读入一些空格或回车
// 而char op[2]用scanf("%s")会忽略空格和回车
char op[2];
scanf("%s%s", op, str);
if (*op == 'I') insert(str);
else printf("%d\n", query(str));
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
leetcode-每日一题899. 有序队列(思维题)
ASP.NET Core依赖注入之旅:3.Service Locator和依赖注入
双指针/滑动窗口问题
383. Ransom Note
从MatePad Pro进化看鸿蒙OS的生态势能
C# 构造函数如人之影子
11. Container With Most Water
论文解读(JKnet)《Representation Learning on Graphs with Jumping Knowledge Networks》
Components of communication - the drop-down menu
【LeetCode】899. 有序队列
Web3 安全风险令人生畏?应该如何应对?
401. Binary Watch
最强分布式锁工具:Redisson
【机器学习】机器学习的基本概念/术语2
Huawei, Lenovo, BAIC, etc. were selected as the first batch of training bases for "Enterprise Digital Transformation and Security Capability Improvement" by the Ministry of Industry and Information Te
PTA递归练习
uniapp 切换 history 路由模
关于 Intel 在 micro-vm 快速启动的探索及实例演示 | 第 36-38 期
MobileVIT实战:使用MobileVIT实现图像分类
请问下这个hologres维表是被缓存了么?怎么直接Finished了









