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 }

转载于:https://www.cnblogs.com/yewei/archive/2012/08/06/2625788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值