Pagini recente » Cod sursa (job #841480) | Cod sursa (job #841309) | Cod sursa (job #559280) | Cod sursa (job #282219) | Cod sursa (job #3274679)
#include <fstream>
#include <string>
using namespace std;
class Trie {
public:
void insert(const string& str, int pos = 0) {
lvs++;
if (pos == int(str.size()))
cnt++;
else {
if (!next[str[pos] - 'a'])
next[str[pos] - 'a'] = new Trie;
next[str[pos] - 'a']->insert(str, pos + 1);
}
}
int count(const string& str, int pos = 0) {
if (pos == int(str.size()))
return cnt;
if (!next[str[pos] - 'a'])
return 0;
return next[str[pos] - 'a']->count(str, pos + 1);
}
int lcp(const string& str, int pos = 0) {
if (pos == int(str.size()))
return 0;
if (!next[str[pos] - 'a'])
return 0;
return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
}
void erase(const string& str, int pos = 0) {
lvs--;
if (pos == int(str.size()))
cnt--;
else {
next[str[pos] - 'a']->erase(str, pos + 1);
if (!next[str[pos] - 'a']->lvs) {
delete next[str[pos] - 'a'];
next[str[pos] - 'a'] = nullptr;
}
}
}
private:
int cnt = 0, lvs = 0;
Trie *next[26] = {};
};
ifstream fin("trie.in");
ofstream fout("trie.out");
int op;
string s;
Trie t;
int main() {
while(fin >> op >> s) {
if(op == 0) {
t.insert(s);
} else if(op == 1) {
t.erase(s);
} else if(op == 2) {
fout << t.count(s) << '\n';
} else {
fout << t.lcp(s) << '\n';
}
}
return 0;
}