参考博客:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
字典树就是单词树,顺着一条路径到达终止结点就形成一个单词,该单词的前缀包含在这条路径中。字典树的一般操作有insert单词和search前缀或者单词。
hdu1251字典树模板链接:http://icpc.njust.edu.cn/Problem/Hdu/1251/
代码如下:唯一要注意的地方就是读入数据,读入空行的时候gets函数读入的是NULL
#include<bits/stdc++.h>
using namespace std;
typedef unsigned int ui;
typedef long long ll;
typedef unsigned long long ull;
#define pf printf
#define mem(a,b) memset(a,b,sizeof(a))
#define prime1 1e9+7
#define prime2 1e9+9
#define pi 3.14159265
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define scand(x) scanf("%llf",&x)
#define f(i,a,b) for(int i=a;i<=b;i++)
#define scan(a) scanf("%d",&a)
#define dbg(args) cout<<#args<<":"<<args<<endl;
#define inf 0x3f3f3f3f
const int maxn=1e6+;
int n,m,t;
char s[maxn],s1[maxn];
int trie[maxn][],sum[maxn];
int cnt=;
void insert(char* s)
{
int rt=;
int len=strlen(s);
f(i,,len-)
{
int c=s[i]-'a';
if(!trie[rt][c])trie[rt][c]=++cnt;
rt=trie[rt][c];
sum[rt]++;
}
}
int find(char* s)
{
int rt=;
int len=strlen(s);
f(i,,len-)
{
int c=s[i]-'a';
if(!trie[rt][c])return ;
rt=trie[rt][c];
}
return sum[rt];
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
std::ios::sync_with_stdio(false);
while(gets(s))
{
if(s[]==NULL)break;//gets读入空行时会转化成NULL
insert(s);
}
while(gets(s))
{
pf("%d\n",find(s));
}
}