Skip to content

Instantly share code, notes, and snippets.

@Chillee
Last active April 13, 2019 04:05
Show Gist options
  • Save Chillee/8a7cb187a3e906c81c6e840bccbb134b to your computer and use it in GitHub Desktop.
Save Chillee/8a7cb187a3e906c81c6e840bccbb134b to your computer and use it in GitHub Desktop.
Trie
struct Trie {
const static int MAXCHAR = 26;
struct Vertex {
int nxt[MAXCHAR];
bool leaf = false;
Vertex() { fill(begin(nxt), end(nxt), -1); }
int &operator[](int x) { return nxt[x]; }
};
Trie() : trie(1) {}
vector<Vertex> trie;
Vertex &operator[](int x) { return trie[x]; }
void add_string(string const &s) {
int v = 0;
for (char ch : s) {
int c = ch - 'a';
if (trie[v][c] == -1) {
trie[v][c] = trie.size();
trie.emplace_back();
}
v = trie[v][c];
}
trie[v].leaf = true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment