Pagini recente » Cod sursa (job #2799393) | Cod sursa (job #470799) | Cod sursa (job #332429) | Cod sursa (job #2449900) | Cod sursa (job #3033342)
#include <fstream>
#include <cstring>
const int NMAX=25;
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct node
{
int cnt, nrc;
node* v[26];
node()
{
cnt=nrc=0;
for(int i=0; i<26; i++) v[i]=NULL;
}
};
typedef node* trie;
void inserare(trie, char*, int);
bool stergere(trie, char*, int);
int nr_ap(trie, char*, int);
int lp(trie, char*, int, int);
bool ok(trie);
trie root;
char s[NMAX];
int tip;
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(0);
fout.tie(0);
root=new node;
while(fin>>tip>>s)
{
if(tip==0) inserare(root, s, strlen(s));
if(tip==1) stergere(root, s, strlen(s));
if(tip==2) fout<<nr_ap(root, s, strlen(s))<<'\n';
if(tip==3) fout<<lp(root, s, strlen(s), 0)<<'\n';
}
return 0;
}
void inserare(trie nod, char* s, int lg)
{
if(lg==0)
{
nod->cnt++;
return;
}
if(nod->v[s[0]-'a']==NULL)
{
nod->v[s[0]-'a']=new node;
nod->nrc++;
}
inserare(nod->v[s[0]-'a'], (s+1), lg-1);
}
bool stergere(trie nod, char* s, int lg)
{
if(lg==0)
{
nod->cnt--;
return ok(nod);
}
if(stergere(nod->v[s[0]-'a'], (s+1), lg-1))
{
delete nod->v[s[0]-'a'];
nod->v[s[0]-'a']=NULL;
nod->nrc--;
return ok(nod);
}
return false;
}
int nr_ap(trie nod, char* s, int lg)
{
if(lg==0) return nod->cnt;
if(nod->v[s[0]-'a']) return nr_ap(nod->v[s[0]-'a'], (s+1), lg-1);
return 0;
}
int lp(trie nod, char* s, int lg, int lvl)
{
if(lg==0) return lvl;
if(nod->v[s[0]-'a']) return max(lvl+1, lp(nod->v[s[0]-'a'], (s+1), lg-1, lvl+1));
return 0;
}
bool ok(trie nod)
{
return (!nod->cnt && !nod->nrc);
}