Pagini recente » Cod sursa (job #1435207) | Cod sursa (job #2933364) | Cod sursa (job #1682631) | Cod sursa (job #1137732) | Cod sursa (job #2221540)
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
using namespace std;
class Trie
{
private:
struct Node {
int words;
int nrsons;
Node* sons[30];
Node() {
words = 0;
nrsons = 0;
for (int i = 0; i < 26; i++) {
sons[i] = nullptr;
}
}
};
Node* root;
bool del(Node* curr, string word, unsigned int index)
{
if(index == word.size())
{
curr->words--;
return curr->nrsons == 0;
}
int c = word[index] - 'a';
Node* node = curr->sons[c];
bool ShouldDelete = del(node, word, index + 1);
if(ShouldDelete)
{
Node* aux = curr->sons[c];
curr->sons[c] = nullptr;
delete aux;
curr->nrsons--;
return curr->nrsons == 0;
}
return 0;
}
public:
Trie(){root = new Node();}
void add(string word)
{
Node* curr = root;
for(unsigned int i = 0; i < word.size(); i++)
{
int c = word[i] - 'a';
if(curr->sons[c] == nullptr)
{
curr->sons[c] = new Node();
}
curr->nrsons++;
curr = curr->sons[c];
}
curr->words++;
}
void del(string word)
{
del(root, word, 0);
}
int cnt(string word)
{
Node* curr = root;
for(unsigned int i = 0; i < word.size(); i++)
{
int c = word[i] - 'a';
if(curr->sons[c] != nullptr)
curr = curr->sons[c];
else return 0;
}
return curr->words;
}
int prefix(string word)
{
int nr = 0;
Node* curr = root;
for(unsigned int i = 0; i < word.size(); i++)
{
int c = word[i] - 'a';
if(curr->sons[c] != nullptr)
{
curr = curr->sons[c];
nr++;
}
else
return nr;
}
return nr;
}
};
int main()
{
ifstream f("trie.in");
ofstream g("trie.out");
Trie trie;
int op;
string s;
while(f >> op >> s)
{
if(op == 0)
trie.add(s);
else if(op == 1)
trie.del(s);
else if(op == 2)
g << trie.cnt(s) << endl;
else
g << trie.prefix(s) << endl;
}
return 0;
}