转载:三叉树

突然想到之前写的三叉树,每次加入一个新子段就会浪费一个本不用着的内存。改了一下。

三叉树上AC自动机写了三天了,还是没有写出来。

普及一下,三叉树很早就有人研究了,主要用途还是用来处理字符串,对于trie树来说,处理含有全部ascill码的字符串就有压力了,更不用说处理中文串了。不过了解的人并不是很多。

粘一下我写的修正后的代码。

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <cstdio>  
  2. #include <cstring>  
  3. #include <queue>  
  4.   
  5. typedef int Nodelink;  
  6. const int maxn = 1000101;//内存池大小  
  7. Nodelink Node[maxn][3];   //三叉树的节点,预开内存的速度是动态开不可比拟的(TLE了一晚的教训)。  
  8. int cnt[maxn];   //以该节点为结束的字符串的数目。  
  9. char elem[maxn];   //节点保存的字符。  
  10. int top;   //模拟内存池地址  
  11. Nodelink newNode(char ch)  
  12. {  
  13.     top ++;  
  14.     Node[top][0] = Node[top][1] = Node[top][2] = 0;  
  15.     cnt[top] = 0;  
  16.     elem[top] = ch;  
  17.     return top;  
  18. }  
  19.   
  20. void insert(char str[])  
  21. {  
  22.     int len = strlen(str);  
  23.     Nodelink p = 1;  
  24.     for(int i = 0; i < len; i++)  
  25.     {  
  26.         if(!Node[p][2])  
  27.             Node[p][2] = newNode(str[i]);  
  28.         p = Node[p][2];  
  29.         while(elem[p] != str[i])  
  30.         {  
  31.             if(str[i] < elem[p])  
  32.             {  
  33.                 if(!Node[p][0]) Node[p][0] = newNode(str[i]);  
  34.                 p = Node[p][0];  
  35.             }  
  36.             else   
  37.             {  
  38.                 if(!Node[p][1]) Node[p][1] = newNode(str[i]);  
  39.                 p = Node[p][1];  
  40.             }  
  41.         }  
  42.     }  
  43.     cnt[p] ++;  
  44. }  
  45.   
  46. char str[30];  
  47.   
  48. void print(Nodelink p, int len)  
  49. {  
  50.     if(Node[p][0])  
  51.         print(Node[p][0], len);  
  52.     str[len] = elem[p];  
  53.   
  54.     if(cnt[p])  
  55.     {  
  56.         str[len + 1] = '\0';  
  57.         for(int i = 0; i < cnt[p]; i++)  
  58.             printf("%s\n", str);  
  59.     }  
  60.   
  61.     if(Node[p][2])  
  62.         print(Node[p][2], len + 1);  
  63.     if(Node[p][1])  
  64.         print(Node[p][1], len);  
  65. }  
  66.   
  67. int main()  
  68. {  
  69.     top = 0;  
  70.     newNode('\0');  
  71.     char str[6][10] = {"she","sir""sre""her""te""she"};  
  72.     for(int i = 0; i < 6; i++)  
  73.         insert(str[i]);  
  74.     print(Node[1][2], 0);  
  75. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值