Pagini recente » Cod sursa (job #2069418) | Cod sursa (job #180172) | Cod sursa (job #177208) | Cod sursa (job #1771693) | Cod sursa (job #1234467)
#include <fstream>
#include <string>
#include <algorithm>
#include <cassert>
struct TrieNode
{
int leaf;
int passing;
TrieNode* next[26];
TrieNode();
void AddWord(const char*);
void RemWord(const char*);
int ComputeAppearances(const char*);
int ComputeMaxSubstr(const char*);
};
TrieNode::TrieNode() : leaf(0), passing(0)
{
for (int i = 0; i < 26; ++i)
next[i] = 0;
}
void TrieNode::AddWord(const char* word)
{
if (!*word){
++leaf;
return;
}
int idx = *word - 'a';
TrieNode* nextNode = next[idx];
if (!nextNode) {
nextNode = new TrieNode();
next[idx] = nextNode;
}
++nextNode->passing;
nextNode->AddWord(word + 1);
}
void TrieNode::RemWord(const char* word)
{
if (!*word) {
--leaf;
return;
}
int idx = *word - 'a';
TrieNode* nextNode = next[idx];
assert(nextNode);
--nextNode->passing;
nextNode->RemWord(word + 1);
}
int TrieNode::ComputeAppearances(const char* word)
{
if (!*word)
return leaf;
TrieNode* nextNode = next[*word - 'a'];
if (!nextNode)
return 0;
return nextNode->ComputeAppearances(word + 1);
}
int TrieNode::ComputeMaxSubstr(const char* word)
{
if (!*word){
return passing ? 0 : -1;
}
TrieNode* nextNode = next[*word - 'a'];
if (!nextNode)
return 0;
if (!nextNode->passing)
return 0;
return 1 + nextNode->ComputeMaxSubstr(word + 1);
}
int main()
{
char line[30];
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
TrieNode* tn = new TrieNode();
while (fin.getline(line, 30)) {
int ret;
switch (*line) {
case '0':
tn->AddWord(line+2);
break;
case '1':
tn->RemWord(line+2);
break;
case '2':
ret = tn->ComputeAppearances(line + 2);
fout << ret << "\n";
break;
case '3':
fout << tn->ComputeMaxSubstr(line + 2) << "\n";
break;
}
}
fin.close();
fout.close();
return 0;
}