<<字典树模板>>
1:字典树,又称单词查找树,Trie树,是一种树形结构,哈希表的一个变种。用于统计,排序和保存大量的字符串(也可以保存其他的)。优点就是利用公共的前缀来节约存储空间。在这举个简单的例子:比如说我们想储存3个单词,sky、skyline、skymoon。如果只是单纯的按照以前的字符数组存储的思路来存储的话,那么我们需要定义三个字符串数组。但是如果我们用字典树的话,只需要定义一个树就可以了。在这里我们就可以看到字典树的优势了。
2 在trie树中,每一个单词对应不同的一条路径。只有当单词完全相同的时候才有可能出现同一个节点有多个单词结尾的情况,所以如果说所有的单词都不同那么以某个节点为结尾的单词数肯定为1。(画图)
3 注意如果是多组的数据一般采用静态分配的方法。
动态分配
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
struct Trie{
int count;/*这个根据需要变化*/
Trie *child[26];
/*初始化节点*/
Trie(){
for(int i = 0 ; i < 26 ; i++)
child[i] = NULL;
count = 0;
}
};
Trie *root;
/*字典树的插入*/
void insert(char *str){
Trie *s = root;
for(int i = 0 ; i < strlen(str) ; i++){
int num = str[i]-'a';
/*如果以str[i]为首的节点为空*/
if(s->child[num] == NULL)
s->child[num] = new Trie();/*创建新的节点*/
s = s->child[num];
(s->count)++;/*以s之前为前缀的字符串的个数*/
}
}
/*字典树的查找*/
int search(char *str){
Trie *s = root;
int tmp_count = 0;
for(int i = 0 ; i < strlen(str) ; i++){
int num = str[i]-'a';
/*如果以str[i]为前缀的节点为空,直接返回0*/
if(s->child[num] == NULL)
return 0;
else{
s = s->child[num];
tmp_count = s->count;
}
}
return tmp_count;
}
int main(){
root = new Trie();
return 0;
}
静态分配
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 100000/*最多的节点个数*/
#define N 30
int cnt;
struct Trie{
int count;/*这个根据需要变化*/
Trie *child[N];
/*初始化节点*/
}trie[MAXN];
Trie *root;
/*静态分配空间*/
Trie* newTrie(){
trie[cnt].count = 0;
for(int i = 0 ; i < N; i++)
trie[cnt].child[i] = NULL;
return &trie[cnt++];
}
/*字典树的插入*/
void insert(char *str){
Trie *s = root;
for(int i = 0 ; i < strlen(str) ; i++){
int num = str[i]-'a';
if(s->child[num] == NULL)
s->child[num] = newTrie();/*创建新的节点*/
s = s->child[num];
}
}
/*字典树的查找*/
bool search(char *str){
Trie *s = root;
int tmp_count = 0;
for(int i = 0 ; i < strlen(str) ; i++){
int num = str[i]-'a';
/*如果以str[i]为前缀的节点为空,直接返回0*/
if(s->chi