Pagini recente » Cod sursa (job #2857522) | Cod sursa (job #748375) | Cod sursa (job #3238074) | Cod sursa (job #615389) | Cod sursa (job #2769276)
#include <fstream>
using namespace std;
struct Trie
{
int nr = 0, c = 0;
Trie *sons[26];
Trie()
{
for (int i = 0; i < 26; i++)
{
sons[i] = NULL;
}
};
void add(const string &s, int poz = 0)
{
c++;
if (poz == s.size())
{
nr++;
return;
}
if (sons[s[poz] - 'a'] == NULL)
{
sons[s[poz] - 'a'] = new Trie;
}
sons[s[poz] - 'a'] -> add(s, poz + 1);
}
void del(const string &s, int poz = 0)
{
c--;
if (poz == s.size())
{
nr--;
return;
}
sons[s[poz] - 'a'] -> del(s, poz + 1);
}
int cnt(string &s, int poz = 0)
{
if (c == 0)
{
return 0;
}
if (poz == s.size())
{
return nr;
}
if (sons[s[poz] - 'a'] != NULL)
{
return sons[s[poz] - 'a'] -> cnt(s, poz + 1);
}
return 0;
}
int pref(string &s, int poz = 0)
{
if (c == 0)
{
return 0;
}
if (poz == s.size())
{
return poz;
}
if (sons[s[poz] - 'a'] != NULL && sons[s[poz] - 'a'] -> c != 0)
{
return sons[s[poz] - 'a'] -> pref(s, poz + 1);
}
return poz;
}
};
Trie *T;
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
T = new Trie;
int tip;
string s;
while (fin >> tip >> s)
{
if (tip == 0)
{
T -> add(s);
}
else if (tip == 1)
{
T -> del(s);
}
else if (tip == 2)
{
fout << T -> cnt(s) << "\n";
}
else
{
fout << T -> pref(s) << "\n";
}
}
return 0;
}