字典树 模板题
使用数组写法
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 1000000 + 10;
int trie[maxn][27];
int pre_sum[maxn];///统计前缀次数
//int vis_word[maxn];///单词是否出现过
int tot = 0;
void t_insert(char str[]){
int root = 0;
int id;
for(int i = 0; str[i]; i++){
id = str[i] - 'a';
if(!trie[root][id])
trie[root][id] = ++tot;
root = trie[root][id];
pre_sum[root]++;
}
}
int t_find(char str[]){
int root = 0;
int id;
for(int i = 0; str[i]; i++){
id = str[i] - 'a';
if(!trie[root][id]) return 0;///没找到这个单词或者前缀
root = trie[root][id];
}
//return 1;
//return vis_word[root];
return pre_sum[root];
}
int main(){
//memset(trie, 0, sizeof(trie));
//memset(pre_sum, 0, sizeof(pre_sum));
//memset(vis_word, 0, sizeof(vis_word));
char str[100];
while(gets(str) && strcmp(str, "") != 0){
t_insert(str);
}
int ans;
while(scanf("%s", str) != EOF)
{
ans = t_find(str);
printf("%d\n", ans);
}
return 0;
}