Pagini recente » Cod sursa (job #3261322) | Cod sursa (job #3249237)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
bool ok = 0;
struct Trie{
struct Node{
Node *c[27];
int count;
int leaves;
Node()
{
count = leaves = 0;
for(int i = 0; i < 27; ++i)
c[i] = nullptr;
}
};
Node *root;
Trie()
{
root = new Node;
}
Node* ret()
{
return root;
}
void insert(string s)
{
Node *node = root;
for(auto &ch: s)
{
if(node -> c[int(ch - 'a')] == nullptr)
{
node -> leaves++;
node -> c[int(ch - 'a')] = new Node;
}
node = node -> c[int(ch - 'a')];
}
node -> count ++;
}
void del(Node *node, string s, int cnt)
{
if(cnt <= s.size() - 1)
del(node -> c[int (s[cnt] - 'a')], s, cnt + 1);
if(cnt == s.size())
{
node -> count--;
}
if(ok == 1)
{
node -> leaves--;
node -> c[int(s[cnt] - 'a')] = nullptr;
ok = 0;
}
if(node -> count == 0 && node -> leaves == 0)
{
ok = 1;
node = nullptr;
}
}
void print(string s)
{
Node *node = root;
for(auto &ch: s)
{
if(node -> c[int(ch - 'a')] == nullptr)
{
fout << "0\n";
return;
}
node = node -> c[int(ch - 'a')];
}
fout << node -> count << "\n";
}
void prefix(string s)
{
Node *node = root;
int cnt = 0;
for(auto &ch: s)
{
if(node -> c[int(ch - 'a')] == nullptr)
break;
cnt++;
node = node -> c[int(ch - 'a')];
}
fout << cnt << "\n";
}
};
int main()
{
int t;
string s;
Trie tr;
try
{
while(fin >> t >> s)
{
switch (t)
{
case 0:
tr.insert(s);
break;
case 1:
ok = 0;
tr.del(tr.ret(), s, 0);
break;
case 2:
tr.print(s);
break;
case 3:
tr.prefix(s);
break;
}
}
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
}