/*
-------------字典树----------
利用主字符串组来构造树
可以查询以模式串为前缀的主字符串的个数
只能查前缀!!!
*/
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
using namespace std;
#define ll long long
#define pi acos(-1)
const int maxn = 1e6+5;
int trie[maxn][26]; //字典树
int book[maxn]; //标记每个节点出现几次
int id; //当前字典树中有几个节点
inline void insert(char *s) //将字符串s插入字典树中
{
int len = strlen(s);
int p = 0; //从0节点开始
for(int i=0;i<len;++i)
{
int c = s[i] - 'a';
if(!trie[p][c]) //没有边,就加边
trie[p][c] = ++id;
p = trie[p][c];
++book[p];
}
}
inline search(char *s) //查找模式串s
{
int len = strlen(s);
int p = 0; //从0节点开始查找
for(int i=0;i<len;++i)
{
int c = s[i] - 'a';
if(!trie[p][c])
return 0;
p = trie[p][c];
}
return book[p]; //返回模式串s在字典树中出现的次数
}
signed main()
{
char ss[505];
while(gets(ss))
{
if(ss[0]=='\0') break;
insert(ss);
}
while(~scanf("%s",ss))
{
printf("%d\n",search(ss));
}
return 0;
}
HDU 1251 [字典树] --by二汪
最新推荐文章于 2024-08-21 18:16:36 发布