Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdbool.h>
- #include <string.h>
- #include <stdlib.h>
- struct trie {
- struct trie* a[26];
- bool term;
- };
- struct trie* init_trie (void) {
- struct trie* t = malloc (sizeof (struct trie));
- t->term = 0;
- for (int i = 0; i < 26; ++i) t->a[i] = NULL;
- return t;
- }
- void add_word (struct trie* t, char* s, int i, int n) {
- if (i == n) {
- t->term = 1;
- return;
- }
- int x = s[i] - 'a';
- if (!t->a[x]) t->a[x] = init_trie ();
- add_word (t->a[x], s, i + 1, n);
- }
- void print_trie (struct trie* t) {
- for (int i = 0; i < 26; ++i) {
- if (t->a[i]) {
- printf ("->%c\n", 'a' + i);
- print_trie (t->a[i]);
- }
- }
- printf ("<-\n");
- }
- void destruct_trie (struct trie* t) {
- for (int i = 0; i < 26; ++i) if (t->a[i]) destruct_trie (t->a[i]);
- free (t);
- }
- int main (void) {
- struct trie* root = init_trie ();
- char* s = malloc ((int)1e4);
- int n;
- scanf ("%d", &n);
- for (int i = 0; i < n; ++i) {
- scanf ("%s", s);
- add_word (root, s, 0, strlen (s));
- }
- print_trie (root);
- destruct_trie (root);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement