字典树

DK大牛最近分遗产,又偷了一个过来,真是好东西!!

算法流程

必须步骤:preprocess

插入:读字符串入a后insert

查找:读字符串入a后find

 

#include < iostream >
using   namespace  std;
struct  node
{
    
bool  f;
    
int  next[ 26 ];
    
void  init(){memset(next, - 1 , sizeof (next));f = 0 ;}
}s[
200000 ];
int  p;
char  a[ 100 ];
void  preprocess(){s[p = 0 ].init();}
void  insert()
{
    
int  index = 0 ;
    
for ( int  i = 0 ;a[i];i ++ )
    {
        
int  x = a[i] - 'a ' ;
        
if (s[index].next[x] ==- 1 )
        {
            s[
++ p].init();
            s[index].next[x]
= p;
        }
        index
= s[index].next[x];
    }
    s[index].f
= 1 ;
}
bool  find()
{
    
int  index = 0 ;
    
for ( int  i = 0 ;a[i];i ++ )
    {
        
int  x = a[i] - 'a ' ;
        
if (s[index].next[x] ==- 1 return   0 ;
        index
= s[index].next[x];
    }
    
return  s[index].f;
}

你可能感兴趣的:(字典树)