Trie树模板题,询问一个前缀在字符串集合中出现的次数。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e6+4;
struct Trie {
int ch[26][N];
int val[N],tot;
inline Trie() {memset(ch,-1,sizeof(ch));memset(val,0,sizeof(val));tot=0;}
inline void Insert(char *s) {
int rt=0;
for (int i=0;s[i];++i) {
if (ch[s[i]-'a'][rt]==-1)
ch[s[i]-'a'][rt]=++tot;
rt=ch[s[i]-'a'][rt];
++val[rt];
}
}
inline int find(char *s) {
int rt=0;
for (int i=0;s[i];++i) {
if (ch[s[i]-'a'][rt]==-1) return 0;
rt=ch[s[i]-'a'][rt];
}
return val[rt];
}
}T;
int n,q;
int main() {
// freopen("hihocoder 1014.in","r",stdin);
scanf("%d",&n);
for (register int i=0;i<n;++i) {
char s[12];
scanf("%s",s);
T.Insert(s);
}
scanf("%d",&q);
for (register int i=0;i<q;++i) {
char s[12];
scanf("%s",s);
printf("%d\n",T.find(s));
}
return 0;
}