Pagini recente » Cod sursa (job #1810730) | Cod sursa (job #1716772) | Cod sursa (job #2642476) | Cod sursa (job #1839360) | Cod sursa (job #1234468)
#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::~TrieNode()
{
for (int i = 0; i < 26; ++i)
delete next[i];
}
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 0;
}
TrieNode* nextNode = next[*word - 'a'];
if (!nextNode || !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;
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;
}