Pagini recente » Cod sursa (job #2273295) | Cod sursa (job #2432580) | Cod sursa (job #2509372) | Cod sursa (job #2792776) | Cod sursa (job #1655769)
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class TrieNode
{
public:
unsigned int elementCount, nChildren;
vector<TrieNode*> children;
TrieNode()
{
elementCount = 0;
nChildren = 0;
children.resize(26);
}
};
class Trie
{
public:
TrieNode* root;
Trie()
{
root = new TrieNode;
}
void Add(string s)
{
TrieNode* current = root;
for (int i = 0; i < s.length(); i++)
{
int idx = s[i] - 97;
if (current->children[idx])
{
current = (current->children[idx]);
}
else
{
TrieNode* node = new TrieNode;
current->nChildren++;
current->children[idx] = node;
current = node;
}
if (i == s.length() - 1)
{
current->elementCount++;
}
}
}
void Remove(string s)
{
_remove(root, s, root);
}
int NumberOfOccurences(string s)
{
TrieNode* current = root;
int i;
for (i = 0; i < s.length(); i++)
{
int idx = s[i] - 97;
if (current->children[idx])
{
current = current->children[idx];
}
else
{
break;
}
}
if (i == s.length())
{
return current->elementCount;
}
return 0;
}
int LogestCommonPrefix(string s)
{
TrieNode* current = root;
int i;
for (i = 0; i < s.length(); i++)
{
int idx = s[i] - 97;
if (current->children[idx])
{
current = current->children[idx];
}
else
{
break;
}
}
return i;
}
void printAllWords(TrieNode* node, string w)
{
TrieNode* current = node;
if (current->elementCount > 0)
{
cout << w << " " << current->elementCount << "\n";
}
for (int i = 0; i < 26; i++)
{
if (current->children[i])
{
printAllWords(current->children[i], w + char(i + 97));
}
}
}
private:
bool _remove(TrieNode* node, string s, TrieNode* root)
{
TrieNode* current = node;
int idx = s[0] - 97;
if (!(s[0]) || s[0] == '\n')
{
current->elementCount--;
}
else if (_remove(current->children[idx], s.substr(1), root))
{
current->children[idx] = NULL;
current->nChildren--;
}
if (current->elementCount == 0 && current->nChildren == 0 && current != root)
{
delete current;
return true;
}
return false;
}
};
int main()
{
int x;
string s;
Trie t;
ifstream f("trie.in");
ofstream g("trie.out");
int cnt = 0;
while (f >> x >> s)
{
if (x == 0)
{
t.Add(s);
}
else if (x == 1)
{
t.Remove(s);
}
else if (x == 2)
{
cnt++;
g << t.NumberOfOccurences(s) << "\n";
//if (cnt == 17)
//{
// t.printAllWords(t.root, "");
//}
}
else if (x == 3)
{
cnt++;
g << t.LogestCommonPrefix(s) << "\n";
}
}
return 0;
}