字典树的基础知识较为简单,其目前看过的基本问题有:
①:前缀类
例如,统计字典树中以某一子串为前缀的单词有多少、输出单词的唯一前缀等;
②:组合类
给定串由多个字典单词构成/由两个构成--------->统计个数/组合方式输出;
③:存在性问题
某一单词是否出现;
字典树树结构中节点的val数组存储的内容有两种基本思路:①标记该点是否为某一单词尾节点(例如:判断某单词是否出现过)②有多少单词经过该节点(例如:统计以某一单词为前缀的单词数)。
一个模板题:
统计字典中以给定字符串为前缀的单词数;
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include<algorithm>
#include <set>
#include <queue>
#include <stack>
#include<vector>
#include<map>
#include<ctime>
#define ll long long
using namespace std;
int trie[410100][30];
char str[122];
int val[400100];
int tot=0;
void insert(char * s)
{
int p=0;
for(int i=0;i<strlen(s);++i)
{
int x=s[i]-'a';
if(trie[p][x]==0)
{
trie[p][x]=++tot;
}
p=trie[p][x];
val[p]++;
}
//delete s;不好用
}
int search(char *s)
{
int p=0;
for(int i=0;i<strlen(s);++i)
{
int x=s[i]-'a';
if(trie[p][x]==0)
{
return 0;
}
p=trie[p][x];
}
// delete s;
return val[p];
}
int main()
{
memset(str,'0',sizeof(str));
memset(val,0,sizeof(val));
memset(trie,0,sizeof(trie));
while(gets(str))
{
if(strcmp(str,"")==0)break;
else insert(str);
memset(str,'0',sizeof(str));
}
while(gets(str))
{
int ans=search(str);
cout<<ans<<endl;
memset(str,'0',sizeof(str));
}
return 0;
}
The end;