Pagini recente » Cod sursa (job #1623308) | Cod sursa (job #630535) | Rating Bilteanu Mihaela Bianca (BiancaBM) | Cod sursa (job #2784244) | Cod sursa (job #2736621)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
class TRIE
{
private:
int frec, cntson;
TRIE* sons[26];
public:
TRIE()
{
frec = cntson = 0;
memset(sons, 0, sizeof(sons));
}
void ADD(string s, int poz)
{
int val = s[poz] - 'a';
if(!sons[val])
{
++cntson;
sons[val] = new TRIE;
}
if(poz == s.size() - 1)
++sons[val]->frec;
else sons[val]->ADD(s, poz + 1);
}
void ERASE(string s, int poz)
{
int val = s[poz] - 'a';
if(poz == s.size() - 1)
--sons[val]->frec;
else sons[val]->ERASE(s, poz + 1);
if(sons[val]->frec == 0 && sons[val]->cntson == 0)
{
delete sons[val];
sons[val] = 0;
--cntson;
}
}
int APARITII(string s, int poz)
{
int val = s[poz] - 'a';
if(sons[val])
{
if(poz == s.size() - 1)
return sons[val]->frec;
else return sons[val]->APARITII(s, poz + 1);
}
else return 0;
}
int LCMPR(string s, int poz){
int val = s[poz] - 'a';
if(sons[val] && poz < s.size())
return sons[val]->LCMPR(s, poz + 1);
else return poz;
}
};
TRIE *root = new TRIE;
int main()
{
int op;
string s;
while(fin >> op >> s){
if(op == 0)
root->ADD(s, 0);
else if(op == 1)
root->ERASE(s, 0);
else if(op == 2)
fout << root->APARITII(s, 0) << '\n';
else fout << root->LCMPR(s, 0) << '\n';
}
return 0;
}