Pagini recente » Cod sursa (job #2391835) | Cod sursa (job #2075265) | Cod sursa (job #2589410) | Cod sursa (job #2885063) | Cod sursa (job #3281765)
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
class TrieNode {
private:
TrieNode *edg[26];
int wordsEnded;
int subtreeSize;
public:
TrieNode() {
memset(edg, 0, sizeof edg);
wordsEnded = 0;
subtreeSize = 0;
}
void add(const string &s, int depth = 0) {
subtreeSize++;
if (depth == s.size()) {
wordsEnded++;
return;
}
int nextLetterIndex = s[depth] - 'a';
if (edg[nextLetterIndex] == NULL)
edg[nextLetterIndex] = new TrieNode();
edg[nextLetterIndex]->add(s, depth + 1);
}
void remove(const string &s, int depth = 0) {
subtreeSize--;
if (depth == s.size()) {
wordsEnded--;
return;
}
int nextLetterIndex = s[depth] - 'a';
edg[nextLetterIndex]->remove(s, depth + 1);
if (edg[nextLetterIndex]->subtreeSize == 0) {
delete edg[nextLetterIndex];
edg[nextLetterIndex] = 0;
}
}
int leastCommonAncestor(const string &s, int depth = 0) {
if (depth == s.size()) {
return depth;
}
int nextLetterIndex = s[depth] - 'a';
if (edg[nextLetterIndex] != nullptr) {
return edg[nextLetterIndex]->leastCommonAncestor(s, depth + 1);
}
return depth;
}
int findWordsEnded (const string &s, int depth = 0) {
if (depth == s.size()) {
return wordsEnded;
}
int nextLetterIndex = s[depth] - 'a';
if (edg[nextLetterIndex] != nullptr) {
return edg[nextLetterIndex]->findWordsEnded(s, depth + 1);
}
return 0;
}
};
int main() {
int operatie;
string word;
TrieNode root;
while (fin >> operatie >> word) {
if (operatie == 0) {
root.add(word);
} else if (operatie == 1) {
root.remove(word );
} else if (operatie == 2) {
fout << root.findWordsEnded(word ) << '\n';
} else if (operatie == 3) {
fout << root.leastCommonAncestor(word) << '\n';
}
}
return 0;
}