Pagini recente » Cod sursa (job #416654) | Cod sursa (job #1095322) | Cod sursa (job #292755) | Cod sursa (job #591317) | Cod sursa (job #1227809)
#include <string>
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node {
int descendants;
int words;
Node* sons[26];
Node(void) {
descendants = words = 0;
for (unsigned int i = 0; i < 26; ++i)
sons[i] = NULL;
}
};
Node* root = new Node();
void InsertNode(Node*, const string&, unsigned int = 0);
bool EraseNode(Node*, const string&, unsigned int = 0);
int CountWords(Node*, const string&, unsigned int = 0);
int CountPrefix(Node*, const string&, unsigned int = 0);
int main()
{
int number; string word;
while ( fin >> number >> word )
{
if ( number == 0 )
InsertNode(root, word);
if ( number == 1 )
EraseNode(root, word);
if ( number == 2 ) fout <<
CountWords(root, word) << '\n';
if ( number == 3 ) fout <<
CountPrefix(root, word) << '\n';
}
fin.close();
fout.close();
return 0;
}
int CountPrefix(Node* node, const string& word, unsigned int depth)
{
if ( depth == word.size() )
return depth;
else
{
int son_position = word[depth] - 'a';
Node* son = node->sons[son_position];
if ( node->sons[son_position] != NULL )
return CountPrefix(node->sons[son_position], word, depth+1);
return depth;
}
}
int CountWords(Node* node, const string& word, unsigned int depth)
{
if ( depth == word.size() )
return node->words;
int son_position = word[depth] - 'a';
if ( node->sons[son_position] != NULL )
return CountWords(node->sons[son_position], word, depth+1);
return 0;
}
bool EraseNode(Node* node, const string& word, unsigned int depth)
{
int son_position = word[depth] - 'a';
if ( depth == word.size() )
--node->words;
else if ( EraseNode(node->sons[son_position], word, depth+1) )
{
--node->descendants;
node->sons[son_position] = NULL;
}
if ( node->words == 0 && node->descendants == 0 && node != root )
{
delete node;
return true;
}
return false;
}
void InsertNode(Node* node, const string& word, unsigned int depth)
{
if ( depth == word.size() )
{
++node->words;
return;
}
int son_position = word[depth] - 'a';
if ( node->sons[son_position] == NULL )
{
node->sons[son_position] = new Node();
++node->descendants;
}
InsertNode(node->sons[son_position], word, depth+1);
}