zoukankan      html  css  js  c++  java
  • 左孩子右兄弟的字典树

    一般写的字典树都是双数组的形式,但是当字符的数量很多时,就会占用大量的内存,初始化操作也会变慢。这时,就可以用左孩子右兄弟的写法,来以时间换空间。

    下面是自己写的一个:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 
     5 using namespace std;
     6 
     7 const int maxnode=100000;
     8 
     9 struct Trie
    10 {
    11     char ch[maxnode];
    12     int left[maxnode],right[maxnode],cnt;
    13     bool flag[maxnode];
    14 
    15     Trie(){}
    16     void init()
    17     {
    18         cnt=1;
    19         left[0]=right[0]=ch[0]=0;
    20         flag[0]=false;
    21         //memset(flag,false,sizeof(flag));
    22     }
    23 
    24     void insert(const char* str)
    25     {
    26         int len=strlen(str),u=0,j;
    27         for(int i=0;i<len;i++)
    28         {
    29             for(j=left[u];j;j=right[j])
    30             {
    31                 if(ch[j]==str[i]) break;
    32             }
    33             if(j==0)///a new node
    34             {
    35                 j=cnt++;
    36                 left[j]=0;ch[j]=str[i];
    37                 flag[j]=false;
    38                 right[j]=left[u];
    39                 left[u]=j;
    40             }
    41             u=j;
    42         }
    43         flag[j]=true;
    44     }
    45 
    46     bool query(const char* str)
    47     {
    48         int len=strlen(str),u=0,j;
    49         for(int i=0;i<len;i++)
    50         {
    51             for(j=left[u];j;j=right[j])
    52             {
    53                 if(ch[j]==str[i]) break;
    54             }
    55             if(j==0) return false;
    56             u=j;
    57         }
    58         return flag[j];
    59     }
    60 
    61 }tree;
    62 
    63 int main()
    64 {
    65     char dic[200];
    66     int d;
    67     tree.init();
    68     while(cin>>d>>dic)
    69     {
    70         if(d==1)
    71         {
    72             tree.insert(dic);
    73         }
    74         else if(d==2)
    75         {
    76             cout<<tree.query(dic)<<endl;
    77         }
    78     }
    79     return 0;
    80 }
  • 相关阅读:
    haproxy 基于 cookie 的会话保持
    haproxy 透明代理
    haproxy tcp keepalive
    haproxy 支持 websocket
    python 中给文件加锁
    使用python生成二维码
    python中的uuid简介
    django建表报错
    pip安装第三方包PIL失败
    python获取mac地址的方法
  • 原文地址:https://www.cnblogs.com/CKboss/p/3417870.html
Copyright © 2011-2022 走看看