标签:
题目链接:http://hihocoder.com/problemset/problem/1014
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 using namespace std; 6 7 const int maxn = 1e6 + 5; // 1e5 * 10 (1e5个单词 * 单词长度 (<= 10)) 8 const int N = 26; 9 10 int le; 11 char str[N]; 12 13 struct Trie 14 { 15 int cnt; 16 int next[N]; 17 void init() { 18 cnt = 0; 19 memset(next, -1, sizeof(next)); 20 } 21 }T[maxn]; 22 23 void Build(char *s) 24 { 25 int i = 0, p = 0; 26 while (s[i]) { 27 int x = s[i] - ‘a‘; 28 if (T[p].next[x] == -1) { 29 T[le].init(); 30 T[p].next[x] = le++; 31 // printf("T[%d].next[%d] = %d, ", p, x, T[p].next[x]); 32 } 33 p = T[p].next[x]; 34 T[p].cnt++; 35 // printf("T[%d].cnt = %d\n", p, T[p].cnt); 36 i++; 37 } 38 } 39 40 void Query(char *s) 41 { 42 int i = 0, p = 0; 43 while (s[i]) { 44 int x = s[i] - ‘a‘; 45 if (T[p].next[x] == -1) { 46 puts("0"); 47 return ; 48 } 49 p = T[p].next[x]; 50 i++; 51 } 52 printf("%d\n", T[p].cnt); 53 } 54 55 int main() 56 { 57 int n, m; 58 #ifndef ONLINE_JUDGE 59 freopen("in.txt", "r", stdin); 60 #endif // ONLINE_JUDGE 61 62 while (scanf("%d", &n) != EOF) { 63 le = 1; 64 T[0].init(); // !root 65 while (n--) { 66 scanf("%s", str); 67 Build(str); 68 } 69 scanf("%d", &m); 70 while (m--) { 71 scanf("%s", str); 72 Query(str); 73 } 74 } 75 return 0; 76 }
标签:
原文地址:http://www.cnblogs.com/windysai/p/4858022.html