hdu 1251(简单trie)

hdu 1251(简单trie)
这道题简单,1Y,开始delete()是用的~trie中写的,0ms,但是内存很大
我以为是trie中的空间没释放掉,所以改用了递归删除,结果500ms,差距阿,以后要注意了
写这道题主要是复习一下,以下是代码,比以前写的简化了很多
#include < iostream >
#include
< algorithm >
#define MaxN 
26
const  char stdt = ' a';
using namespace std;
struct trie
{
    trie
*   next [MaxN];
    
int  val;
    trie()
    {
        
int  i;
        
for (i = 0 ;i < MaxN;i ++ ) next [i] = 0 ;
        val
= 0 ;
    }
    ~trie()
    {
        
int  i;
        
for (i = 0 ;i < MaxN;i ++ )delete( next [i]);
    }
};
int  main()
{
    char words[
12 ], * t;
    
int  ans;
    trie
*  root = new  trie, * p;
    
while (gets(words) && strcmp(words, "" )){
        p
= root;
        t
= words;
        
while ( * t){
            
if (p -> next [ * t - stdt] == 0 )
                p
-> next [ * t - stdt] = new  trie;
            p
= p -> next [ * t - stdt];
            (p
-> val) ++ ;
            t
++ ;
        }
    }
    
while (scanf( " %s " ,words)! = EOF){
        p
= root;
        t
= words;
        
while ( * t){
            
if (p -> next [ * t - stdt] == 0 ){
                ans
= 0 ; break;}
            p
= p -> next [ * t - stdt];
            ans
= p -> val;
            t
++ ;
        }
        printf(
" %d\n " ,ans);
    }
    return 
0 ;
}

你可能感兴趣的:(hdu 1251(简单trie))