Pagini recente » Cod sursa (job #2669355) | Cod sursa (job #2964367) | Cod sursa (job #930084) | Cod sursa (job #2948024) | Cod sursa (job #1821772)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int op;
char cuv[30];
struct Trie
{
int cont;
int nrSons;
Trie *son[26];
Trie(){
cont=nrSons=0;
memset(son,0,sizeof(son));
}
};
Trie *T = new Trie;
void add(Trie *nod, char *word)
{
if(*word=='\0')
{
nod->cont++;
return;
}
if(nod->son[*word-'a']==0)
{
nod->son[*word-'a'] = new Trie;
nod->nrSons++;
}
add(nod->son[*word-'a'],word+1);
}
int del(Trie *nod, char *word)
{
if(*word=='\0')
{
nod->cont--;
}
else if(del(nod->son[*word-'a'],word+1))
{
nod->son[*word-'a']=0;
nod->nrSons--;
}
if(nod->cont==0 && nod->nrSons==0 && nod!=T)
{
delete nod;
return 1;
}
return 0;
}
int getApp(Trie *nod,char *word)
{
if(*word=='\0')
return nod->cont;
if(nod->son[*word-'a'])
return getApp(nod->son[*word-'a'],word+1);
return 0;
}
int getPrefix(Trie *nod, char *word,int nr)
{
if(*word=='\0' || nod->son[*word-'a']==0)
return nr;
return getPrefix(nod->son[*word-'a'],word+1,nr+1);
}
void run()
{
fin>>op;
fin>>cuv;
while(!fin.eof())
{
switch(op)
{
case 0:
add(T,cuv);
break;
case 1:
del(T,cuv);
break;
case 2:
fout<<getApp(T,cuv)<<"\n";
break;
case 3:
fout<<getPrefix(T,cuv,0)<<"\n";
break;
}
fin>>op;
fin>>cuv;
}
}
int main()
{
run();
return 0;
}