当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
HCIP---Multiple Spanning Tree Protocol related knowledge points
KMP 字符串匹配问题
游戏元宇宙发展趋势展望分析
JS prototype hasOwnProperty in 加方法 原型终点 继承 重写父类方法
scikit-learn no moudule named six
SQL injection of WEB penetration
Postman 批量测试接口详细教程
如何给 UE4 场景添加游戏角色
How to prevent governance attacks in DAOs?
Small program -- subcontracting
随机推荐
SAP ABAP OData 服务如何支持删除(Delete)操作试读版
教你VSCode如何快速对齐代码、格式化代码
小程序毕设作品之微信美食菜谱小程序毕业设计成品(5)任务书
Ten years after graduation, financial freedom: those things that are more important than hard work, no one will ever teach you
小程序毕设作品之微信体育馆预约小程序毕业设计成品(2)小程序功能
使用 Zokrates 在 BSV 上创建您的第一个 zkSNARK 证明
seaborn笔记:可视化统计关系(散点图、折线图)
Uses of Anacoda
leetcode 204. Count Primes 计数质数 (Easy)
Unity Shader general lighting model code finishing
使用Jenkins做持续集成,这个知识点必须要掌握
小程序毕设作品之微信美食菜谱小程序毕业设计成品(6)开题答辩PPT
深度学习Course2第一周Practical aspects of Deep Learning习题整理
程序员必备的 “ 摸鱼神器 ” 来了 !
scikit-learn no moudule named six
LeetCode952三部曲之二:小幅度优化(137ms -> 122ms,超39% -> 超51%)
[@synthesize in Objective-C]
Kubernetes Scheduler全解析
Implementation principle of VGUgarbage collector (garbage collector)
迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation