Pagini recente » Cod sursa (job #1140184) | Cod sursa (job #2292444) | Cod sursa (job #1516775) | Cod sursa (job #1185585) | Cod sursa (job #2073332)
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
struct Trie {
int isEnd, isPassed;
vector<Trie*> next;
Trie() {
isEnd = 0;
isPassed = 0;
for (int i = 0; i < 26; i ++)
next.push_back(NULL);
}
};
Trie *t = new Trie();
void add(Trie *&tr, string word, int k) {
tr->isPassed ++;
if (k == word.size()) {
tr->isEnd ++;
return;
}
if (!tr->next[word[k] - 'a']) {
tr->next[word[k] - 'a'] = new Trie();
}
add(tr->next[word[k] - 'a'], word, k + 1);
}
void remove(Trie *&tr, string word, int k) {
tr->isPassed --;
if (k == word.size()) {
if (tr->isEnd > 0)
tr->isEnd --;
return;
}
if (!tr->next[word[k] - 'a']) {
return;
}
remove(tr->next[word[k] - 'a'], word, k + 1);
}
int count(Trie *&tr, string word, int k) {
if (k == word.size()) {
return tr->isEnd;
}
if (!tr->next[word[k] - 'a']) {
return 0;
}
return count(tr->next[word[k] - 'a'], word, k + 1);
}
int prefix(Trie *&tr, string word, int k) {
if (k == word.size() && tr->isPassed > 0) {
return word.size();
}
if (!tr->next[word[k] - 'a'] || tr->next[word[k] - 'a']->isPassed == 0) {
return k;
}
return prefix(tr->next[word[k] - 'a'], word, k + 1);
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
string command;
while (getline(cin, command)) {
if (command[0] == '0') {
add(t, command.substr(2), 0);
}
if (command[0] == '1') {
remove(t, command.substr(2), 0);
}
if (command[0] == '2') {
cout << count(t, command.substr(2), 0) << endl;
}
if (command[0] == '3') {
cout << prefix(t, command.substr(2), 0) << endl;
}
}
return 0;
}