Trie[字典树] 数据结构及基本操作集
2024-08-23 16:07:49
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define Max 26
typedef struct TrieNode *Trie;
struct TrieNode
{
Trie next[Max];
int num;
TrieNode()
{
for (int i = ; i < Max; i++)
next[i] = NULL;
num = ;
}
}; void Insert(Trie root,char *s)
{
Trie p = root;
for (int i = ; s[i]; i++) {
int t = s[i]-'a';
if (p->next[t] == NULL)
p->next[t] = new TrieNode;
p = p->next[t];
}
p->num++;
} void Delete(Trie root, char *s)
{
int len = strlen(s);
Trie p = root;
for (int i = ; i < len; i++) {
int t = s[i]-'a';
if (p->next[t] == NULL)
return;
p = p->next[t];
}
p->num--;
} bool Search(Trie root, char *s)
{
Trie p = root;
if (p == NULL)
return ;
int len = strlen(s);
for (int i = ; i < len; i++) {
int t = s[i]-'a';
if (p->next[t] == NULL)
return ;
p = p->next[t];
}
return p->num > ;
} void PrintDic(Trie root, vector<vector<char> > &words, vector<char> &word)
{
if (root == NULL)
return;
if (root->num > )
words.push_back(word);
for (int i = ; i < Max; i++) {
if (root->next[i]) {
word.push_back('a'+i);
PrintDic(root->next[i], words, word);
word.pop_back();
}
}
} void FreeTrie(Trie root)
{
for (int i = ; i < Max; i++) {
if (root->next[i] != NULL)
FreeTrie(root->next[i]);
}
delete root;
} int main()
{
freopen("1.txt", "r", stdin);
Trie root = new TrieNode;
char s[];
while (cin >> s) {
Insert(root, s);
}
//char temp[50] = "avvvvefaf";
//cout << Search(root, temp);
//Delete(root, temp);
//cout << Search(root, temp); vector<char> word;
vector<vector<char> >words;
PrintDic(root, words, word);
for (int i = ; i < words.size(); i++) {
for (int j = ; j < words[i].size(); j++) {
printf("%c", words[i][j]);
}
printf("\n");
} return ;
}
最新文章
- Python 之 lambda 函数
- 【转】Android Studio中通过快捷键来提取提取方法
- iOS CALayer动画中使用的3个tree
- blend 从无到有系列之添加自定义Rectangle样式指定到资源文件
- [BS-18] 对OC中不可变类的理解
- Newspaper Headline_set(upper_bound)
- java多线程之:深入JVM锁机制2-Lock (转载)
- zend studio 13 curl 请求本机地址 无法跟踪调试的问题解决方案。。。(chrome等浏览器调试原理相同)
- iOS学习之视图控制器
- Codeforces Round #180 (Div. 2) B. Sail 贪心
- Top 12 Best Free Network Monitoring Tools (12种免费网络监控工具)
- Coprimes - SGU 102(求互质数,水)
- sublime 3 3083验证码
- 关于myeclipse中导入的项目修改项目名使得发布到tomcat访问路径正确
- 【80端口占用】win7下80端口被(Pid=4)占用的解决方法
- 基于视觉的Web页面分页算法VIPS的实现源代码下载
- tomcat配置没啥难的啊
- loadrunner 关联函数web_reg_save_param
- webpack模块定义和使用的模式
- 001_自定义过滤及添加文件内容脚本(nginx)