字典树是一种高效快速存储和查询字符串的数据结构,形态上为一个多叉树
用到Trie树的字符串一般都是大写或者都是小写,或者都是数字,或者是01(反正不会有很多种字符)
输入n1和n2,分别表示存入n1个字符串和查询n2次字符串,每次查询都输出该字符串存储了几次。
#include <iostream>
using namespace std;
const int N = 100010;
int son[N][26], cnt[N], idx; //cnt(count)以下标为p的点的为结尾的单词数量
char str[N];
void insert(char str[])
{
int p = 0;
for (int i = 0; str[i]; i++) //因为c++中字符串数组以\0结尾,所以是否到结尾用str[i]判断
{
int u = str[i] - 'a';
if (!son[p][u]) son[p][u] = ++idx;
p = son[p][u];
}
cnt[p]++;
}
int query(char str[])
{
int p = 0;
for (int i = 0; str[i]; i++)
{
int u = str[i] - 'a';
if (!son[p][u]) return 0;
p = son[p][u];
}
return cnt[p];
}
int main()
{
int n1, n2;
cin >> n1 >> n2;
while (n1--)
{
cin >> str;
insert(str);
}
while (n2--)
{
cin >> str;
cout << query(str) << endl;
}
return 0;
}