hdu 1251(字典树)

 1 /*
 2 *  字典树 
 3 */
 4 #include <cstdio>
 5 #include <cstdlib>
 6 #include <cstring>
 7 #include <iostream>
 8 
 9 using namespace std;
10 
11 const int N = 11;
12 
13 char str[N];
14 struct node {//节点数据 
15     int c;  //统计前缀个数 
16     node *child[26];
17     node() {//初始化 
18         c = 1;
19         for (int i=0; i<26; ++i) child[i] = NULL;
20     }
21 }*root;
22 
23 void insert(char str[]) {
24     node *p = root;
25     for (int k,i=0; str[i]; ++i, p=p->child[k]) {
26         k = str[i] - 'a';
27         if (p->child[k]) ++p->child[k]->c;
28         else p->child[k] = new node();
29     }
30 }
31 
32 int search(char str[]) {
33     node *p = root;
34     for (int k,i=0; str[i]; ++i) {
35         k = str[i] - 'a';
36         if (p->child[k]) p = p->child[k];
37         else return 0;
38     }
39     return p->c;
40 }
41 
42 int main() {
43     root = new node();
44     while (gets(str), strcmp(str, "")) insert(str);
45     while (scanf("%s", str) != EOF) printf ("%d\n", search(str));
46     return 0;
47 }

 

posted on 2012-05-07 21:52  Try86  阅读(123)  评论(0)    收藏  举报