字典树
struct Trie { static constexpr int N = 1000010, M = 26; int tot; int tr[N][M]; int ends[N], prefix[N]; void clear() { for(int i = 0; i <= tot; i++) memset(tr[i], 0, sizeof(tr[i])); for(int i = 0; i <= tot; i++) ends[i] = prefix[i] = 0; tot = 0; ends[p] = 0; } Trie() { tot = 0; } void insert(string &s) { int p = 0; for(auto &ch : s) { int c = ch - 'a'; if(tr[p][c] == 0) tr[p][c] = ++tot; p = tr[p][c]; prefix[p] ++; } ends[p] ++; }}tr;
01 字典树
struct Trie { static constexpr int N = 600005, M = 2; int tot; int tr[N][M]; int ends[N], prefix[N]; void clear() { for(int i = 0; i <= tot; i++) memset(tr[i], 0, sizeof(tr[i])); for(int i = 0; i <= tot; i++) ends[i] = prefix[i] = 0; tot = 0; } Trie() { tot = 0; } void insert(int x) { int p = 0; for(int i = 30; i >= 0; i--) { int c = x >> i & 1; if(tr[p][c] == 0) tr[p][c] = ++tot; p = tr[p][c]; prefix[p] ++; } } int ask(int x) { int p = 0, rs = 0; for(int i = 30; i >= 0; i--) { int c = x >> i & 1; if (tr[p][c ^ 1]) { p = tr[p][c ^ 1]; rs |= 1 << i; } else if(tr[p][c]) { p = tr[p][c]; } else { return 0; } } return rs; }}tr;