【数据结构学习笔记】字典树 上——竞赛版、工程版代码
竞赛版
#include <stdio.h>
#define MAX_N 1000000
struct Node {
int flag;
int next[26];
} tree[MAX_N + 5];
int node_cnt = 1, root = 0;
int getNewNode() {
return node_cnt++;
}
void insert(const char *str) {
int p = root;
for (int i = 0; str[i]; i++) {
int ind = str[i] - 'a';
if (tree[p].next[ind] == 0) tree[p].next[ind] = getNewNode();
p = tree[p].next[ind];
}
tree[p].flag = 1;
}
int find(const char *str) {
int p = root;
for (int i = 0; str[i]; i++) {
p = tree[p].next[str[i] - 'a'];
if (p == 0) return 0;
}
return tree[p].flag;
}
void output(int p, int k, char *buff) {
if (!p) return ;
if (p == -1) p = 0;
buff[k] = 0;
if (tree[p].flag) printf("%s\n", buff);
for (int i = 0; i < 26; i++) {
buff[k] = 'a' + i;
output(tree[p].next[i], k + 1, buff);
}
return ;
}
char str[MAX_N + 5];
int main() {
int op;
while (~scanf("%d", &op)) {
switch (op) {
case 1: scanf("%s", str);
printf("insert %s to the Trie!\n", str);
insert(str);
break;
case 2: scanf("%s", str);
printf("find %s from the Trie = %d.\n", str, find(str));
break;
case 3: printf("All list:\n");
output(-1, 0, str);
break;
}
}
return 0;
}
工艺版
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BASE 26
typedef struct Node {
int flag;
struct Node *next[BASE];
} Node;
Node *getNewNode() {
Node *p = (Node *)malloc(sizeof(Node));
p->flag = 0;
memset(p->next, 0, sizeof(Node *) * BASE);
return p;
}
void insert(Node *root, const char *str) {
Node *p = root;
for (int i = 0; str[i]; i++) {
int ind = str[i] - 'a';
if (p->next[ind] == NULL) p->next[ind] = getNewNode();
p = p->next[ind];
}
p->flag = 1;
return ;
}
int find(Node *root, const char *str) {
Node *p = root;
for (int i = 0; str[i]; i++) {
p = p->next[str[i] - 'a'];
if (p == NULL) return 0;
}
return p->flag;
}
void output(Node *root, int k, char *buff) {
if (root == NULL) return ;
buff[k] = 0;
if (root->flag) printf("%s\n", buff);
for (int i = 0; i < BASE; i++) {
buff[k] = 'a' + i;
output(root->next[i], k + 1, buff);
}
return ;
}
void clear(Node *root) {
if (root == NULL) return ;
for (int i = 0; i < BASE; i++) {
clear(root->next[i]);
}
free(root);
return ;
}
int main() {
int op;
char str[100];
Node *root = getNewNode();
while (~scanf("%d", &op)) {
switch (op) {
case 1: scanf("%s", str);
printf("insert %s to the trie!\n");
insert(root, str);
break;
case 2: scanf("%s", str);
printf("find %s from the trie = %d\n", str, find(root, str));
break;
case 3: output(root, 0, str);
break;
}
}
return 0;
}
练习题:
AcWing 835. Trie字符串统计 - AcWing
#281. 前缀统计 OJ - Online Judge (haizeix.com)
#282. 最大异或对OJ - Online Judge (haizeix.com)
#283. 拨号 OJ - Online Judge (haizeix.com)
…
…