Pagini recente » Cod sursa (job #3208882) | Cod sursa (job #3180428) | Cod sursa (job #267552) | Cod sursa (job #544707) | Cod sursa (job #1720434)
#include <fstream>
#include <cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
class Trie {
private:
int nrFii;
int nrCuv;
Trie* fii[26];
void addRec(Trie *nod, char *s) {
if(*s == 0) {
nod->nrCuv++;
return;
}
if(nod->fii[*s - 'a'] == NULL) {
nod->fii[*s - 'a'] = new Trie();
nod->nrFii++;
}
addRec(nod->fii[*s - 'a'], s + 1);
}
bool delRec(Trie *nod, char *s) {
if(*s == 0) {
nod->nrCuv--;
} else {
if(delRec(nod->fii[*s - 'a'], s + 1)) {
nod->fii[*s - 'a'] == 0;
nod->nrFii--;
}
}
if(nod->nrFii == 0 && nod->nrCuv == 0 && nod != this) {
delete nod;
return true;
}
return false;
}
int freqRec(Trie *nod, char *s) {
if(*s == 0) {
return nod->nrCuv;
}
if(nod->fii[*s - 'a'] != 0) {
return freqRec(nod->fii[*s - 'a'], s + 1);
}
return 0;
}
int lgPrefixrec(Trie *nod, char *s) {
if(*s == 0 || nod->fii[*s - 'a'] == 0) {
return 0;
}
return lgPrefixrec(nod->fii[*s - 'a'], s + 1) + 1;
}
public:
Trie() {
nrFii = 0;
nrCuv = 0;
memset(fii, 0, sizeof(fii));
}
void add(char *s) {
this->addRec(this, s);
}
void del(char *s) {
this->delRec(this, s);
}
int freq(char *s) {
return this->freqRec(this, s);
}
int lgPrefix(char *s) {
return lgPrefixrec(this, s);
}
};
ifstream fin("trie.in");
ofstream fout("trie.out");
Trie *t = new Trie();
int main() {
char line[30];
int op;
while(fin.getline(line, 30)) {
switch(line[0]) {
case '0' : t->add(line + 2); break;
case '1' : t->del(line + 2); break;
case '2' : fout << t->freq(line + 2) << "\n"; break;
case '3' : fout << t->lgPrefix(line + 2) <<"\n"; break;
default : break;
}
}
fin.close();
fout.close();
return 0;
}