Pagini recente » Diferente pentru runda/inceput intre reviziile 2 si 8 | Profil annost | Diferente pentru runda/concurs_pd intre reviziile 8 si 7 | Atasamentele paginii blabla | Cod sursa (job #2021666)
#include<fstream>
#include<string>
using namespace std;
ifstream is("trie.in");
ofstream os("trie.out");
struct TRIE
{
int nr_cuv;
int nr_fii;
TRIE* Next[27];
};
TRIE* Root;
void Add(string w, TRIE* T);
void Remove(string w, TRIE* T);
int Count(string w, TRIE* T);
int Prefix(string w, TRIE* T);
int main()
{
int op;
string w;
Root = new TRIE();
while (is >> op >> w)
{
switch (op)
{
case 0: Add(w, Root); break;
case 1: Remove(w, Root); break;
case 2: os << Count(w, Root) << '\n'; break;
case 3: os << Prefix(w, Root) << '\n'; break;
}
}
is.close();
os.close();
return 0;
}
void Add(string w, TRIE* T)
{
if (w == "")
{
T->nr_cuv++;
return;
}
if (T->Next[w[0] - 97] == NULL)
{
T->Next[w[0] - 97] = new TRIE();
T->nr_fii++;
}
Add(w.substr(1), T->Next[w[0] - 97]);
}
void Remove(string w, TRIE* T)
{
if (w == "")
{
T->nr_cuv--;
return;
}
Remove(w.substr(1), T->Next[w[0] - 97]);
if (T->Next[w[0] - 97]->nr_cuv == 0 && T->Next[w[0] - 97]->nr_fii == 0)
{
T->Next[w[0] - 97] = NULL;
T->nr_fii--;
return;
}
}
int Count(string w, TRIE* T)
{
if (T == NULL)
return 0;
if (w == "")
return T->nr_cuv;
return Count(w.substr(1), T->Next[w[0] - 97]);
}
int Prefix(string w, TRIE* T)
{
if (T->Next[w[0] - 97] == NULL || w == "")
return 0;
return Prefix(w.substr(1), T->Next[w[0] - 97]) + 1;
}