当前位置:网站首页>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;
}
边栏推荐
- 【时间的比较】
- 为什么我用了Redis之后,系统的性能却没有提升
- 使用deepstream消息发送功能的时候,检测框没有检测标签,No text labels of bboxes displayed with osd for deepstream-test5
- “LaMDA 存在种族歧视,谷歌的 AI 伦理不过是‘遮羞布’!”
- 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
- sphinx error connection to 127.0.0.1:9312 failed (errno=0, msg=)
- J9数字虚拟论:元宇宙的潜力:一股推动社会进步的力量
- 微信小程序 - 数组 push / unshift 追加后数组返回内容为数字(数组添加后打印结果为 Number 数值类型)
- PMP试题 | 每日一练,快速提分
- How to write SQL statements in DataWorks monitoring data reaches a certain value to indicate the change of
猜你喜欢
“LaMDA 存在种族歧视,谷歌的 AI 伦理不过是‘遮羞布’!”
【目标检测】Focal Loss for Dense Object Detection
组件通信--下拉菜单案例
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
After using Stream for many years, does collect still have these "saucy operations"?
[redis] cache penetration and cache avalanche and cache breakdown solutions
软件测试<用例篇>
【数据库数据恢复】SqlServer数据库无法读取的数据恢复案例
火热的印度工厂,带不动印度制造
sphinx coreseek的安装和php下使用
随机推荐
ORACLE CLOUD 在国内有数据中心吗?
为什么我用了Redis之后,系统的性能却没有提升
TiKV & TiFlash accelerate complex business queries丨TiFlash application practice
【云驻共创】【HCSD大咖直播】亲授大厂面试秘诀
我想请问下,我们的数据库是在亚马逊,Dataworks 连不通,怎么办?
isNotBlank与isNotEmpty
沃尔沃:这是会“种草”的“安全感”!
【Metaverse系列一】元宇宙的奥秘
出海,是泡泡玛特的“解药”吗?
论文解读(JKnet)《Representation Learning on Graphs with Jumping Knowledge Networks》
华为、联想、北汽等入选工信部“企业数字化转型和安全能力提升”首批实训基地
国内首发可视化智能调优平台,小龙带你玩转KeenTune UI
The strongest distributed lock tool: Redisson
产品-Axure9英文版,轮播图效果
383. Ransom Note
组件通信-父传子组件通信
兄弟组件通信context
Async的线程池使用的哪个?
phoenix创建映射表和创建索引、删除索引
LyScript 从文本中读写ShellCode