HDOJ 1251 -- 统计难题 Trie

来源:互联网 发布:美工抠图总结 编辑:程序博客网 时间:2024/05/01 18:37

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

/* PROG:   统计难题 ID  :    LANG:   C++ */ #include <string> #include <cstdio> #include <cstdlib> #include <memory.h> #include <iostream> #include <algorithm> using namespace std;  struct Trie_Node {     int  cnt;     Trie_Node *branch[27];     Trie_Node():cnt( 0 )     {         memset( branch, 0, sizeof(branch) );     }// Init };  class Trie {     public:         Trie();         void Trie_Insert( char ss[] );         int  Trie_Find( char ss[] );              private:         Trie_Node *root; }t;  Trie::Trie() {     root = new Trie_Node(); }// Trie  void Trie::Trie_Insert( char ss[] ) {     Trie_Node *ptr = root;     Trie_Node *temp = NULL;     int slen = strlen( ss );     for ( int i=0; i<slen ;++i )     {         if ( ptr->branch[ ss[i]-'a' ]==NULL )         {             temp = new Trie_Node();             ptr->branch[ ss[i]-'a' ] = temp;         }                  ++( ptr->branch[ ss[i]-'a' ]->cnt );         ptr = ptr->branch[ ss[i]-'a' ];     }// Insert          return ; }// Trie_Insert  int Trie::Trie_Find( char ss[] ) {     int i, slen = strlen( ss );     Trie_Node *ptr = root;     for ( i=0; i<slen; ++i )     {         ptr = ptr->branch[ ss[i]-'a' ];         if ( ptr==NULL )    break;     }          if ( i==slen )         return ( ptr->cnt );     else         return 0; }// Trie_Find  int main() {     char vocabu[12];     while ( gets( vocabu ) )     {         if ( !strcmp( vocabu, "" ) )    break;         t.Trie_Insert( vocabu );     }// creat the trie          while ( EOF != scanf("%s", vocabu) )     {         printf("%d\n", t.Trie_Find( vocabu ));     }// Find the prefix          return 0; }


原创粉丝点击