Pagini recente » Rating Stefan Lupascu (Yellowflash) | Cod sursa (job #2306983) | Cod sursa (job #1674154) | Cod sursa (job #2220328) | Cod sursa (job #1844772)
#include <fstream>
#include <string>
#include <unordered_map>
using namespace std;
struct Node
{
int count = 0;
unordered_map<char, Node*> sons;
};
void Insert(Node *t, const string &s)
{
for (char c : s) {
if (t->sons.find(c) == t->sons.end()) {
t->sons.insert({c, new Node()});
}
t = t->sons[c];
}
t->count += 1;
}
int Delete(Node *t, const string &s, unsigned pos = 0)
{
if (pos == s.size()) {
t->count -= 1;
} else if (t->sons.find(s[pos]) != t->sons.end()) {
if (Delete(t->sons[s[pos]], s, pos + 1)) {
t->sons.erase(s[pos]);
}
}
if (t->count == 0 && t->sons.size() <= 0 && pos > 0) {
delete t;
return 1;
}
return 0;
}
int FindCount(Node *t, const string &s)
{
for (char c : s) {
if (t->sons.find(c) == t->sons.end()) {
return 0;
}
t = t->sons[c];
}
return t->count;
}
int FindPrefix(Node *t, const string &s)
{
int len = 0;
for (char c : s) {
if (t->sons.find(c) == t->sons.end()) {
return len;
}
++len;
t = t->sons[c];
}
return len;
}
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
Node *trie = new Node();
int opt;
string word;
while (fin >> opt >> word) {
if (opt == 0) {
Insert(trie, word);
} else if (opt == 1) {
Delete(trie, word);
} else if (opt == 2) {
fout << FindCount(trie, word) << "\n";
} else if (opt == 3) {
fout << FindPrefix(trie, word) << "\n";
}
}
return 0;
}