Pagini recente » Cod sursa (job #2819083) | Cod sursa (job #2908584) | Cod sursa (job #371994) | Cod sursa (job #2929644) | Cod sursa (job #1576910)
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
#define MaxC 21
struct Nod {
Nod() {
nr_cuv = nr_sons = 0;
memset(son, 0, sizeof son);
}
int nr_cuv, nr_sons;
Nod* son[26];
};
Nod* T = new Nod;
char sir[21];
void Insert(Nod* nod, char* s);
bool Delete(Nod* nod, char* s);
int Count (Nod* nod, char* s);
int Prefix(Nod* nod, char* s, int k);
int main() {
while(fin.getline(sir, MaxC )) {
switch(sir[0]) {
case '0': Insert(T, sir + 2); break;
case '1': Delete(T, sir + 2); break;
case '2': fout << Count (T, sir + 2) << '\n'; break;
case '3': fout << Prefix(T, sir + 2, 0) << '\n'; break;
}
}
fin.close();
fout.close();
return 0;
}
int Prefix(Nod *nod, char *s, int k )
{
if ( *s == '\0' || nod->son[*s - 'a'] == 0 )
return k;
return Prefix( nod->son[*s - 'a'], s + 1, k + 1 );
}
int Count(Nod* nod, char* s ) {
if ( *s == '\0' )
return nod->nr_cuv;
if ( nod->son[*s - 'a'] )
return Count( nod->son[*s - 'a'], s + 1 );
return 0;
}
bool Delete(Nod* nod, char* s ) {
if ( *s == '\0' ) {
nod->nr_cuv--;
}
else {
if ( Delete(nod->son[*s - 'a'], s + 1) ) {
nod->son[*s - 'a'] = 0;
nod->nr_sons--;
}
}
if ( nod->nr_cuv == 0 && nod->nr_sons == 0 && nod != T ) {
delete nod;
return true;
}
return false;
}
void Insert(Nod* nod, char* s ) {
if ( *s == '\0' ) {
nod->nr_cuv++;
return;
}
if ( nod->son[*s - 'a'] == 0 ) {
nod->son[*s - 'a'] = new Nod;
nod->nr_sons++;
}
Insert(nod->son[*s - 'a'], s + 1);
}