HDOJ 1251 -- 统计难题 Trie

Trie的写法是很灵活的,感觉跟segment tree一样,要活用

 1 /*
 2 PROG:   统计难题
 3 ID  :   ouyangyewei
 4 LANG:   C++
 5 */
 6 #include <string>
 7 #include <cstdio>
 8 #include <cstdlib>
 9 #include <memory.h>
10 #include <iostream>
11 #include <algorithm>
12 using namespace std;
13 
14 struct Trie_Node
15 {
16     int  cnt;
17     Trie_Node *branch[27];
18     Trie_Node():cnt( 0 )
19     {
20         memset( branch, 0, sizeof(branch) );
21     }// Init
22 };
23 
24 class Trie
25 {
26     public:
27         Trie();
28         void Trie_Insert( char ss[] );
29         int  Trie_Find( char ss[] );
30         
31     private:
32         Trie_Node *root;
33 }t;
34 
35 Trie::Trie()
36 {
37     root = new Trie_Node();
38 }// Trie
39 
40 void Trie::Trie_Insert( char ss[] )
41 {
42     Trie_Node *ptr = root;
43     Trie_Node *temp = NULL;
44     int slen = strlen( ss );
45     for ( int i=0; i<slen ;++i )
46     {
47         if ( ptr->branch[ ss[i]-'a' ]==NULL )
48         {
49             temp = new Trie_Node();
50             ptr->branch[ ss[i]-'a' ] = temp;
51         }
52         
53         ++( ptr->branch[ ss[i]-'a' ]->cnt );
54         ptr = ptr->branch[ ss[i]-'a' ];
55     }// Insert
56     
57     return ;
58 }// Trie_Insert
59 
60 int Trie::Trie_Find( char ss[] )
61 {
62     int i, slen = strlen( ss );
63     Trie_Node *ptr = root;
64     for ( i=0; i<slen; ++i )
65     {
66         ptr = ptr->branch[ ss[i]-'a' ];
67         if ( ptr==NULL )    break;
68     }
69     
70     if ( i==slen )
71         return ( ptr->cnt );
72     else
73         return 0;
74 }// Trie_Find
75 
76 int main()
77 {
78     char vocabu[12];
79     while ( gets( vocabu ) )
80     {
81         if ( !strcmp( vocabu, "" ) )    break;
82         t.Trie_Insert( vocabu );
83     }// creat the trie
84     
85     while ( EOF != scanf("%s", vocabu) )
86     {
87         printf("%d\n", t.Trie_Find( vocabu ));
88     }// Find the prefix
89     
90     return 0;
91 }
posted @ 2012-08-06 21:52  Maxwell:My Blog  阅读(333)  评论(0编辑  收藏  举报