Pagini recente » Cod sursa (job #1142388) | Cod sursa (job #1616921) | Cod sursa (job #2635272) | Cod sursa (job #1006159) | Cod sursa (job #1717441)
#include <fstream>
#include <cstring>
#define Size_Of_Alphabet 26
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
class Trie
{
public :
int cnt, nr_sons;
Trie *son[Size_Of_Alphabet];
Trie()
{
cnt = nr_sons = 0;
memset(son, NULL, sizeof(son));
}
};
Trie *T = new Trie;
char Line[32];
void Ins(Trie *nod, char *s)
{
if (*s == NULL)
{
nod->cnt += 1;
return;
}
if (nod->son[*s - 'a'] == NULL)
{
nod->son[*s - 'a'] = new Trie;
nod->nr_sons += 1;
}
Ins(nod->son[*s - 'a'], s + 1);
}
bool Del(Trie *nod, char *s)
{
if (*s == NULL)
{
nod->cnt -= 1;
}
else if (Del(nod->son[*s - 'a'], s + 1))
{
nod->son[*s - 'a'] = NULL;
nod->nr_sons -= 1;
}
if (nod->cnt == 0 && nod->nr_sons == 0 && nod != T)
{
delete nod;
return true;
}
return false;
}
int Nr_Aparitii(Trie *nod, char *s)
{
if (*s == NULL)
{
return nod->cnt;
}
if (nod->son[*s - 'a'] != NULL)
{
return Nr_Aparitii(nod->son[*s - 'a'], s + 1);
}
return 0;
}
int Max_Prefix(Trie *nod, char *s, int k)
{
if (*s == NULL || nod->son[*s - 'a'] == NULL)
{
return k;
}
return Max_Prefix(nod->son[*s - 'a'], s + 1, k + 1);
}
int main()
{
while (fin.getline(Line, 30))
{
switch(Line[0])
{
case '0' :
{
Ins(T, Line + 2);
break;
}
case '1' :
{
Del(T, Line + 2);
break;
}
case '2' :
{
fout << Nr_Aparitii(T, Line + 2) << '\n';
break;
}
case '3' :
{
fout << Max_Prefix(T, Line + 2, 0) << '\n';
break;
}
}
}
fin.close();
fout.close();
return 0;
}