Pagini recente » Cod sursa (job #2114228) | Cod sursa (job #3172592) | Cod sursa (job #291584) | Cod sursa (job #1516859) | Cod sursa (job #2381098)
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
class TrieNode
{
vector<TrieNode*> children;
int cnt = 0;
public:
TrieNode()
{
children.resize(30, nullptr);
}
void insert(string const& s, int index = 0)
{
if (index == s.size())
{
++cnt;
return;
}
if (children[s[index] - 'a'] == nullptr)
children[s[index] - 'a'] = new TrieNode();
children[s[index] - 'a']->insert(s, index + 1);
}
bool remove(string const& s, int index = 0)
{
if (index == s.size())
{
--cnt;
return cnt <= 0 && children.empty();
}
if (children[s[index] - 'a'] != nullptr)
{
bool removeNext = children[s[index] - 'a']->remove(s, index + 1);
if (removeNext)
delete children[s[index] - 'a'],
children[s[index] - 'a'] = nullptr;
return cnt <= 0 && children.empty();
}
}
int count(string const& s, int index = 0)
{
if (index == s.size())
return cnt;
if (children[s[index] - 'a'] != nullptr)
return children[s[index] - 'a']->count(s, index + 1);
else
return 0;
}
int prefix(string const& s, int index = 0)
{
if (index == s.size())
return s.size();
if (children[s[index] - 'a'] != nullptr)
return children[s[index] - 'a']->prefix(s, index + 1);
else
return index;
}
};
int main()
{
int op;
string s;
TrieNode trie;
while (!f.eof() && f >> op >> s)
switch (op)
{
case 0:
trie.insert(s);
break;
case 1:
trie.remove(s);
break;
case 2:
g << trie.count(s) << '\n';
break;
case 3:
g << trie.prefix(s) << '\n';
break;
}
return 0;
}