Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <map>
- using namespace std;
- struct node {
- int parent;
- map<char, int> to;
- string str;
- node(int parent, string &str) {
- this->parent = parent;
- this->str = str;
- }
- };
- vector<node> trie;
- void init() {
- trie.push_back(node(-1, string("")));
- }
- void split(int n, int pos) {
- trie.push_back(node(trie[n].parent, trie[n].str.substr(0, pos)));
- trie[trie[n].parent].to[trie[n].str[0]] = trie.size() - 1;
- trie[trie.size() - 1].to[trie[n].str[pos]] = n;
- trie[n].str = trie[n].str.substr(pos);
- }
- void add(string &str) {
- int curnode = 0;
- int curpos = 0;
- for (int i = 0; i < str.length(); i++) {
- if (curpos < trie[curnode].str.length()) {
- if (trie[curnode].str[curpos] == str[i]) {
- curpos++;
- continue;
- } else {
- split(curnode, curpos);
- curnode = trie.size() - 1;
- }
- }
- if (trie[curnode].to.count(str[i]) == 0) {
- trie.push_back(node(curnode, str.substr(i)));
- trie[curnode].to[str[i]] = trie.size() - 1;
- }
- curnode = trie[curnode].to[str[i]];
- curpos = 1;
- }
- if (curpos < trie[curnode].str.length()) {
- split(curnode, curpos);
- curnode = trie.size() - 1;
- }
- if (trie[curnode].to.count('$') == 0) {
- trie[curnode].to['$'] = -1;
- }
- }
- bool contains(string &str) {
- int curnode = 0;
- int curpos = 0;
- for (int i = 0; i < str.length(); i++) {
- if (curpos < trie[curnode].str.length()) {
- if (trie[curnode].str[curpos] == str[i]) {
- curpos++;
- continue;
- } else {
- return false;
- }
- }
- if (trie[curnode].to.count(str[i]) == 0) {
- return false;
- }
- curnode = trie[curnode].to[str[i]];
- curpos = 1;
- }
- if (curpos < trie[curnode].str.length()) {
- return false;
- }
- if (trie[curnode].to.count('$') == 0) {
- return false;
- }
- return true;
- }
- int main() {
- init();
- while (true) {
- string command;
- cin >> command;
- if (command == "exit") {
- break;
- } else if (command == "+") {
- string str;
- cin >> str;
- add(str);
- } else if (command == "?") {
- string str;
- cin >> str;
- cout << (contains(str) ? "YES" : "NO") << endl;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement