1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 5 using namespace std; 6 7 struct node 8 { 9 int next[26]; 10 int cnt; 11 void init() 12 { 13 cnt=0; 14 memset(next,-1,sizeof(next)); 15 } 16 }T[1000000]; 17 18 int le; //第几个字典序 19 20 void insert(char *s) 21 { 22 int i=0,p=0; 23 while(s[i]) 24 { 25 int x=s[i]-'a'; 26 if(T[p].next[x]==-1) 27 { 28 T[le].init(); 29 T[p].next[x] = le++; 30 } 31 p=T[p].next[x]; 32 T[p].cnt++; 33 i++; 34 } 35 } 36 void query(char *s) 37 { 38 int i=0,p=0; 39 while(s[i]) 40 { 41 int x=s[i]-'a'; 42 if(T[p].next[x]==-1) 43 { 44 puts("0"); 45 return ; 46 } 47 p=T[p].next[x]; 48 i++; 49 } 50 printf("%d ",T[p].cnt); 51 } 52 int main() 53 { 54 int n,m; 55 char str[20]; 56 scanf("%d",&n); 57 le=1; 58 T[0].init(); 59 while(n--) { 60 scanf("%s",str); 61 insert(str); 62 } 63 scanf("%d",&m); 64 while(m--) { 65 scanf("%s",str); 66 query(str); 67 } 68 }
const int maxn = 6e5 + 20; const int sigma_size = 3; struct Node { int cnt; bool isEnd; Node *next[sigma_size]; } trie[maxn]; typedef Node Trie; int cnt_node = 0; void insert_Trie (char *str, Trie *root) { root -> cnt ++; if (str[0] == 0) { root -> isEnd = 1; return ; } if (root -> next[str[0] - 'a'] == 0) { cnt_node ++; root -> next[str[0] - 'a'] = trie + cnt_node; root -> isEnd = 0; } insert_Trie (str + 1, root -> next[str[0] - 'a']); }