突然想到之前写的三叉树,每次加入一个新子段就会浪费一个本不用着的内存。改了一下。
三叉树上AC自动机写了三天了,还是没有写出来。
普及一下,三叉树很早就有人研究了,主要用途还是用来处理字符串,对于trie树来说,处理含有全部ascill码的字符串就有压力了,更不用说处理中文串了。不过了解的人并不是很多。
粘一下我写的修正后的代码。
- #include <cstdio>
- #include <cstring>
- #include <queue>
- typedef int Nodelink;
- const int maxn = 1000101;//内存池大小
- Nodelink Node[maxn][3]; //三叉树的节点,预开内存的速度是动态开不可比拟的(TLE了一晚的教训)。
- int cnt[maxn]; //以该节点为结束的字符串的数目。
- char elem[maxn]; //节点保存的字符。
- int top; //模拟内存池地址
- Nodelink newNode(char ch)
- {
- top ++;
- Node[top][0] = Node[top][1] = Node[top][2] = 0;
- cnt[top] = 0;
- elem[top] = ch;
- return top;
- }
- void insert(char str[])
- {
- int len = strlen(str);
- Nodelink p = 1;
- for(int i = 0; i < len; i++)
- {
- if(!Node[p][2])
- Node[p][2] = newNode(str[i]);
- p = Node[p][2];
- while(elem[p] != str[i])
- {
- if(str[i] < elem[p])
- {
- if(!Node[p][0]) Node[p][0] = newNode(str[i]);
- p = Node[p][0];
- }
- else
- {
- if(!Node[p][1]) Node[p][1] = newNode(str[i]);
- p = Node[p][1];
- }
- }
- }
- cnt[p] ++;
- }
- char str[30];
- void print(Nodelink p, int len)
- {
- if(Node[p][0])
- print(Node[p][0], len);
- str[len] = elem[p];
- if(cnt[p])
- {
- str[len + 1] = '\0';
- for(int i = 0; i < cnt[p]; i++)
- printf("%s\n", str);
- }
- if(Node[p][2])
- print(Node[p][2], len + 1);
- if(Node[p][1])
- print(Node[p][1], len);
- }
- int main()
- {
- top = 0;
- newNode('\0');
- char str[6][10] = {"she","sir", "sre", "her", "te", "she"};
- for(int i = 0; i < 6; i++)
- insert(str[i]);
- print(Node[1][2], 0);
- }