Here is the array notation:
#include <cstdio> #include <string> #include <cstdlib> #include <cstring> #include <iostream > #include <algorithm>using namespace std; #define IDX (x) x-' a '; const int MAXN = 1e6;struct Trie {int next[26 ]; int Val;} Tree[maxn];int NXT, T;char str[maxn];int Add () {memset (&tree[nxt], 0, sizeof (Trie)); return nxt++;} void Insert (char *s) {int rt = 0, Len = strlen (s); for (int i = 0; i < len; i++) {int c = idx (s[i]); if (!tree[rt].next[c]) {Tree[rt].next[c] = Add (); } RT = Tree[rt].next[c]; } tree[rt].val++;} BOOL Find (char *s) {int rt = 0, Len = strlen (s); for (int i = 0; i < len; i++) {int c = idx (s[i]); if (!tree[rt].next[c]) return false; RT = Tree[rt].next[c]; } if (Tree[rt].val) return true; return false;} int main () {memset (&tree[0], 0, sizeof (Trie)); NXT = 1; scanf ("%d", &t); while (t--) {scanf ("%s", str); Insert (str); } while (~SCANF ("%s", str)) {if (Find (str)) puts ("exist"); Else puts ("none"); } return 0;}
here is the static pointer pool notation:
#include <cstdio> #include <string> #include <cstdlib> #include <cstring> #include <iostream > #include <algorithm>using namespace std; #define IDX (x) x-' a '; const int MAXN = 1e6;struct Trie {Trie *next[26]; int Val;} Tree[maxn];int NXT, T;char STR[MAXN]; Trie *add () {memset (&tree[nxt], 0, sizeof (Trie)); return &tree[nxt++];} void Insert (Trie *rt, char *s) {int len = strlen (s); for (int i = 0; i < len; i++) {int c = idx (s[i]); if (!rt->next[c]) rt->next[c] = Add (); RT = rt->next[c]; } rt->val++;} BOOL Find (Trie *rt, char *s) {int len = strlen (s); for (int i = 0; i < len; i++) {int c = idx (s[i]); if (!rt->next[c]) return false; RT = rt->next[c]; } if (Rt->val) return true; return false;} int main () {NXT = 0; Trie *root = Add (); scanf ("%d", &t); while (t--) {scanf ("%s", str); Insert (root, str); } while (~SCANF ("%s", str)) {if (Find (root, str)) puts ("exist"); Else puts ("none"); } return 0;}
"Trie" Trie dictionary tree template static pointer pool, array notation