当前位置:网站首页>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;
}
边栏推荐
- 组件通信-父传子组件通信
- 被误解的 MVC 和被神化的 MVVM(一)
- php之相似文章标题similar_text()函数使用
- EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
- sphinx error connection to 127.0.0.1:9312 failed (errno=0, msg=)
- 如何在 DataWorks 中 写SQL语句监控数据的变化到达一定的值 进行提示
- [Unity Starter Plan] Making RubyAdventure01 - Player Creation & Movement
- 5. Longest Palindromic Substring
- 出海,是泡泡玛特的“解药”吗?
- CAD如何自定义快捷键
猜你喜欢
Detailed explanation of setting HiSilicon MMZ memory and OS memory
LeetCode·899.有序队列·最小表示法
为何微博又双叒叕崩溃了?
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
leetcode-每日一题899. 有序队列(思维题)
【数据库数据恢复】SqlServer数据库无法读取的数据恢复案例
“68道 Redis+168道 MySQL”精品面试题(带解析),你背废了吗?
华为ECS云服务器上安装Docker及部署Redis详细教程【华为云至简致远】
A complete detailed tutorial on building intranet penetration ngrok (with pictures and truth)
JVS低代码移动端接入方案
随机推荐
如何避免无效的沟通
请问下这个hologres维表是被缓存了么?怎么直接Finished了
从MatePad Pro进化看鸿蒙OS的生态势能
组件通信--下拉菜单案例
ORACLE CLOUD 在国内有数据中心吗?
sibling component communication context
After using Stream for many years, does collect still have these "saucy operations"?
Interviews are no longer hanged!This is the correct way to open the seven schemes of Redis distributed locks
Components of communication - the drop-down menu
论文解读(JKnet)《Representation Learning on Graphs with Jumping Knowledge Networks》
JS中对象数组用sort按属性排序
error:Illegal instruction (core dumped),离线下载安装这个other版本numpy
国内首发可视化智能调优平台,小龙带你玩转KeenTune UI
星巴克输血赶不上流血
LeetCode·72.编辑距离·动态规划
PMP考试通关宝典-敏捷专题
405. Convert a Number to Hexadecimal
CC2530_ZigBee+华为云IOT:设计一套属于自己的冷链采集系统
大型企业数据治理的现状和解决方案有哪些参考?_光点科技
EasyExcel实现动态列解析和存表