左儿子有兄弟trie树

好吧,以前没写过,晚上花了些时间实现了一下。

有一个地方我用的二级指针,用引用是不行的,原因是,一旦给引用赋值了,引用的变量就不会改变了,所以容易会出问题。

代码如下HOJ2981求最使用最多的前缀,如果次数相同取字典序最小。

左儿子右兄弟的思路就是一句话:如果当前节点的key和要查询串的当前位置不一样就向右儿子查询,如果一样就向左儿子查询。

代码如下:自认为比较直观,虽然依然很挫的代码= =!

 

HOJ 2981
  1 /*
2 * =====================================================================================
3 *
4 * Filename: trie.cpp
5 *
6 * Description:
7 *
8 * Version: 1.0
9 * Created: 2011/7/19 22:28:47
10 * Revision: none
11 * Compiler: gcc
12 *
13 * Author: YOUR NAME (),
14 * Company:
15 *
16 * =====================================================================================
17 */
18 #include <iostream>
19 #include <cstring>
20 #include <cstdio>
21 usingnamespace std;
22 constint N =100010;
23 char ans[N], tmp[N];
24 int ansLength;
25 class trie_tree
26 {
27 public:
28 class node;
29 void insert(char*from)
30 {
31 node** p =&root;
32 for (char*i = from; *i;)
33 {
34 if(*p == NULL)
35 {
36 (*p) = pp++;
37 (*p)->key =*i;
38 (*p)->count =1;
39 p =&(*p)->left;
40 i++;
41 }
42 else
43 {
44 if((*p)->key ==*i)
45 {
46 (*p)->count++;
47 p =&(*p)->left;
48 i++;
49 }
50 else p =&(*p)->right;
51 }
52 }
53 }
54 void dfs(int len){dfs(len, root);}
55 void build()
56 {
57 pp = pool;
58 root = NULL;
59 memset(pool, 0, sizeof(pool));
60 }
61 private:
62 staticconstint SIZE =1001000;
63 struct node
64 {
65 node *left, *right;
66 int count;
67 char key;
68 } pool[SIZE],*root,*pp;
69 void dfs(int len, node* now)
70 {
71 if(now == NULL) return;
72 if(now->count >1)
73 {
74 tmp[len -1] = now->key;
75 tmp[len] =0;
76 if(ansLength < len || (ansLength == len && strcmp(tmp, ans) ==-1))
77 {
78 ansLength = len;
79 strcpy(ans, tmp);
80 }
81 }
82 dfs(len +1, now->left);
83 dfs(len, now->right);
84 }
85 }tree;
86
87 int main()
88 {
89 int n, cases =0;
90 while(scanf("%d", &n) ==1&& n)
91 {
92 tree.build();
93 getchar();
94 for(int i =0;i < n;i++)
95 {
96 gets(tmp);
97 tree.insert(tmp);
98 }
99 tmp[0] =0;
100 ansLength =0;
101 tree.dfs(1);
102 printf("Case %d: %d\n%s\n",++cases, ansLength, tmp);
103 }
104 return0;
105 }

 

  其实dfs对trie树做了深度优先搜索,两个尾递归不要放在if里面了,不然就错了,因为儿子不是按照cnt从大到小排的,也不是按字母序排的……这么错了一次。

你可能感兴趣的:(trie)