当前位置:网站首页>String - Trie
String - Trie
2022-08-01 22:07:00 【ThXe】
Trie
维护一个字符串集合,支持两种操作:
I x 向集合中插入一个字符串 x;
Q x 询问一个字符串在集合中出现了多少次.
Suppose the sum of all string lengths is n,The time complexity of building a dictionary tree is O(n)
Suppose the length of the string you are looking for is k,查找的时间复杂度为O(k)
拓展应用:
1.A string is a prefix of how many strings are in the collection
解法:Each node can be counted
//Trie树快速存储字符集合和快速查询字符集合
//支持大小写+数字
#include<bits/stdc++.h>
using namespace std;
const int N = 3000001;
//son[][]存储子节点的位置,分支最多26条;
//cnt[]存储以某节点结尾的字符串个数(同时也起标记作用)
//idx表示当前要插入的节点是第几个,每创建一个节点值+1
int son[N][65], cnt[N], idx;
char str[N];
int getnum(char x) {
if (x >= 'A' && x <= 'Z')
return x - 'A';
else if (x >= 'a' && x <= 'z')
return x - 'a' + 26;
else
return x - '0' + 52;
}
void insert(char* str)
{
int p = 0; //类似指针,指向当前节点
for (int i = 0; str[i]; i++)
{
int u =getnum(str[i]); //将字母转化为数字
if (!son[p][u]) son[p][u] = ++idx; //该节点不存在,创建节点
p = son[p][u]; //使“p指针”指向下一个节点
cnt[p]++; //结束时的标记,也是记录以此节点结束的字符串个数(前缀)
}// cnt[p]++出现次数
}
int query(char* str)
{
int p = 0;
for (int i = 0; str[i]; i++)
{
int u = getnum(str[i]);
if (!son[p][u]) return 0; //该节点不存在,即该字符串不存在
p = son[p][u];
}
return cnt[p]; //返回字符串出现的次数
}
int main()
{
int t; cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
for (int i = 0; i <= idx; i++)
for (int j = 0; j <= 64; j++)
son[i][j] = 0;
for (int i = 0; i <= idx; i++)
cnt[i] = 0;
idx = 0;
for (int i = 1; i <= n; i++)
{
cin >> str;
insert(str);
}
for (int i = 1; i <= m; i++)
{
cin >> str;
cout << query(str)<<endl;
}
}
return 0;
}
边栏推荐
猜你喜欢
APP专项测试:流量测试
Kubernetes Scheduler全解析
毕业十年,财富自由:那些比拼命努力更重要的事,从来没人会教你
Unity Shader general lighting model code finishing
今年的很美味
(翻译)按钮的对比色引导用户操作的方式
小程序毕设作品之微信美食菜谱小程序毕业设计成品(8)毕业设计论文模板
Mini Program--Independent Subcontracting & Subcontracting Pre-download
scikit-learn no moudule named six
365 days challenge LeetCode1000 questions - Day 046 Generate a string with odd number of each character + add two numbers + valid parentheses
随机推荐
第3讲:MySQL数据库中常见的几种表字段数据类型
【建议收藏】ヾ(^▽^*)))全网最全输入输出格式符整理
SOM Network 1: Principles Explained
游戏元宇宙发展趋势展望分析
shell规范与变量
9. SAP ABAP OData 服务如何支持删除(Delete)操作
用户体验 | 如何度量用户体验?
基于 OData 模型和 JSON 模型的 SAP UI5 表格控件行项目的添加和删除实现
03、GO语言变量定义、函数
[Mobile Web] Mobile terminal adaptation
三、mysql 存储引擎-建库建表操作
User Experience | How to Measure User Experience?
Ten years after graduation, financial freedom: those things that are more important than hard work, no one will ever teach you
熟悉的朋友
JS prototype hasOwnProperty in 加方法 原型终点 继承 重写父类方法
[机缘参悟-58]:《素书》-5-奉行仁义[遵义章第五]
【C语言实现】求两个整数的较大值
(翻译)按钮的对比色引导用户操作的方式
深度学习Course2第二周Optimization Algorithms习题整理
小程序容器+自定义插件,可实现混合App快速开发