当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
为何微博又双叒叕崩溃了?
如何避免无效的沟通
CC2530_ZigBee+华为云IOT:设计一套属于自己的冷链采集系统
浅谈Service&nbsp;Mesh对业务系统的价值
ASP.NET Core依赖注入之旅:3.Service Locator和依赖注入
401. Binary Watch
一键进入华为云会议,长期免费值得所有开发团队有一套【华为云至简致远】
A complete detailed tutorial on building intranet penetration ngrok (with pictures and truth)
腾讯电竞的蓝翔梦
Excuse me this hologres dimension table is cached?How to Finished
EasyExcel实现动态列解析和存表
高效的组织信息共享知识库是一种宝贵的资源
LeetCode·1163.按字典序排在最后的子串·最小表示法
After using Stream for many years, does collect still have these "saucy operations"?
“LaMDA 存在种族歧视,谷歌的 AI 伦理不过是‘遮羞布’!”
[Unity Getting Started Plan] Basic Concepts (7) - Input Manager & Input Class
102. 最佳牛围栏
SwinIR combat: record the training process of SwinIR in detail
一些嵌入式软件设计经验
【数据库数据恢复】SqlServer数据库无法读取的数据恢复案例









