Pagini recente » Cod sursa (job #2766744) | Cod sursa (job #1175498) | Cod sursa (job #990967) | Cod sursa (job #685769) | Cod sursa (job #2452992)
#include <fstream>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
class Trie {
private:
int cnt = 0;
int ptrs = 0;
Trie *next[26] = {};
public:
void insert(char* str) {
if (!str[0])
cnt++;
else {
if (!next[str[0] - 'a']) {
next[str[0] - 'a'] = new Trie;
ptrs++;
}
next[str[0] - 'a']->insert(str + 1);
}
}
bool remove(char* str) {
if (!str[0])
return --cnt == 0 && !ptrs;
if (next[str[0] - 'a']->remove(str + 1)) {
delete next[str[0] - 'a'];
next[str[0] - 'a'] = NULL;
return --ptrs == 0 && !cnt;
}
return false;
}
int count(char* str) {
if (!str[0])
return cnt;
if (!next[str[0] - 'a'])
return 0;
return next[str[0] - 'a']->count(str + 1);
}
int lcp(char* str) {
if (!str[0] || !next[str[0] - 'a'])
return 0;
return 1 + next[str[0] - 'a']->lcp(str + 1);
}
};
int main() {
Trie trie;
int type; char str[25];
while (fin >> type >> str) {
if (!type)
trie.insert(str);
else if (type == 1)
trie.remove(str);
else if (type == 2)
fout << trie.count(str) << '\n';
else
fout << trie.lcp(str) << '\n';
}
fout.close();
return 0;
}