题意:给定一些单词和一些前缀,问每个前缀出现多少次
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
第一次写trie树,数组开小交上去TLE调了好久
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 5 const int MAXN = 2333666; 6 int s[MAXN], g[MAXN][26], n; 7 char str[20]; 8 9 int find (char str[]) { 10 int x = 1; 11 for (int i = 0; str[i]; ++i) { 12 char ch = str[i]; 13 if (g[x][ch - 'a'] == 0) return 0; 14 x = g[x][ch - 'a']; 15 } 16 return s[x]; 17 } 18 19 void add (char str[]) { 20 int x = 1; 21 ++s[1]; 22 for (int i = 0; str[i]; ++i) { 23 char ch = str[i]; 24 if (g[x][ch - 'a'] == 0) { 25 g[x][ch - 'a'] = ++n; 26 } 27 x = g[x][ch - 'a']; 28 ++s[x]; 29 } 30 } 31 32 int main() { 33 n = 1; 34 while (gets(str) && str[0] != NULL) { 35 add(str); 36 } 37 while (gets(str) && str[0] != NULL) { 38 printf("%d\n", find(str)); 39 } 40 return 0; 41 }