题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题意
统计出以某个单词作为前缀的单词的数量,单词本身也属于单词的前缀。如字符串abc的前缀为a,ab,abc。
思路
字典树模板题目,在往字典树内插入一个单词时,每个经过的结点的sum值都加1,最后通过前缀单词到达的结点的sum值输出答案。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e6+10;
int tree[maxn][30];//tree[i][j]表示节点i的第j个儿子的节点编号
int sum[maxn];//记录节点访问次数
int tot;//总节点数
char s[maxn];
void insert_(char *str)
{
int len=strlen(str);
int root=0;
for(int i=0;i<len;i++){
int id=str[i]-'a';
if(!tree[root][id]) tree[root][id]=++tot;
sum[tree[root][id]]++;
root=tree[root][id];
}
}
int find_(char *str)
{
int len=strlen(str);
int root=0;
for(int i=0;i<len;i++){
int id=str[i]-'a';
if(!tree[root][id]) return 0;
root=tree[root][id];
}
return sum[root];//返回当前字符串结尾节点的访问次数,也就是作为前缀的出现次数
}
int main()
{
while(gets(s)){
if(s[0]=='\0') break;
insert_(s);
}
while(~scanf("%s",s)){
printf("%d\n",find_(s));
}
return 0;
}