题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1251
题目大意:
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
分析:
读入单词直接插入即可,由于这里要查询的是以该前缀为起始的单词数量,所以在加单词的时候,不仅要在单词末尾加值,同时在路径上所有结点都应该价值,最后查询该单词的权值即可
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include<cstdio> #include<algorithm> #include<iostream> #include<cstring> #include<cmath> using namespace std;
typedef long long ll;
struct Trie{ Trie *next[26]; int val; Trie(){ val = 0; for (int i = 0 ; i < 26 ; i ++) next[i] = NULL; } };
void addword(char *str,Trie* node) { if (node->next[str[0]-'a']==NULL) { node->next[str[0]-'a'] = new Trie; node = node->next[str[0]-'a']; node->val ++; } else { node = node->next[str[0]-'a']; node->val ++; } //printf("%c\t",*str); str++; if (*str) addword(str,node); else return; }
int query(char *str ,Trie *node) { //printf("%c\t",*str); if (node->next[*str-'a']==NULL) return 0; else node= node->next[*str-'a']; ++str; if (*str) return query(str,node); else return node->val; }
char str[100];
int main() { Trie *head = new Trie; char ch; int cnt ; while (ch=getchar()) { cnt = 0; if (ch=='\n') break;
while (ch!='\n') { str[cnt++] = ch; ch = getchar(); } str[cnt]=0; addword(str,head); }
while (~scanf("%s",str)) { int ans = query(str,head); printf("%d\n",ans); } return 0; }
|