Pagini recente » Profil educational | Cod sursa (job #1680144) | Cod sursa (job #1635743) | Cod sursa (job #671679) | Cod sursa (job #2221745)
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
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;
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) {
vector<Node*> visited;
visited.push_back(root);
Node* curr = root;
for (unsigned int i = 0; i < word.size(); i++) {
int c = word[i] - 'a';
curr = curr->sons[c];
visited.push_back(curr);
}
curr->words--;
int curr_index = (int)word.size() - 1;
while (visited.size() > 1) {
Node* last = visited.back();
visited.pop_back();
if (last->words !=0 || last->nrsons != 0) {
break;
}
Node* father = visited.back();
father->sons[word[curr_index--] - 'a'] = nullptr;
father->nrsons--;
delete last;
}
}
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)
{
switch (op) {
case 0:
trie.add(s);
break;
case 1:
trie.del(s);
break;
case 2:
g << trie.cnt(s) << '\n';
break;
default:
g << trie.prefix(s) << '\n';
}
}
return 0;
}