Pagini recente » Cod sursa (job #2356899) | Cod sursa (job #887447) | Cod sursa (job #212862) | Cod sursa (job #2592658) | Cod sursa (job #229001)
Cod sursa(job #229001)
#include <fstream>
#include <string>
using namespace std;
const int NrCar='z'-'a'+2,NMAX=21;
class trie{
public:
int nr_words,nr_sons;
trie *leg[NrCar];
trie(){
nr_words=nr_sons=0;
memset(leg,0,sizeof(leg));
}
~trie(){
delete [] leg;
}
void add(string word);
int search(string word);
void erase(string word);
int prefix(string word);
};
void trie::add(string word){
int i;
trie *r=this;
for (i=0;i<word.length();++i){
if (!r->leg[word[i]-'a'])
r->leg[word[i]-'a']=new trie(),++r->nr_sons;
r=r->leg[word[i]-'a'];
r->nr_sons++;}
r->nr_words++;
}
int trie::search(string word){
int i;
trie *r=this;
for (i=0;i<word.length();++i){
if (!r->leg[word[i]-'a']) return 0;
r=r->leg[word[i]-'a'];}
return r->nr_words;
}
int trie::prefix(string word){
int i;
trie *r=this;
for (i=0;i<word.length();++i){
if (!r->leg[word[i]-'a']) return i;
r=r->leg[word[i]-'a'];}
return i;
}
void trie::erase(string word){
int i;
trie *r=this,*aux=r;
bool ok=true;
r=r->leg[word[0]-'a'];
for (i=1;i<word.length() && ok;++i){
r->nr_sons--;
if (r->nr_sons==0) {delete r;
aux->leg[word[i-1]-'a']=0;
ok=false;}
else {aux=r;
r=r->leg[word[i]-'a'];}
}
if (ok) {r->nr_sons--,r->nr_words--;
if (r->nr_sons==0) {delete r;
aux->leg[word[i-1]-'a']=0;}
}
}
ifstream f("trie.in");
ofstream g("trie.out");
string s,word;
trie *t=new trie();
int main(){
while (!f.eof()){
getline(f,s);
if (s.length()<3) continue;
word=s.substr(2,NMAX);
switch (s[0]){
case '0': t->add(word);break;
case '1': t->erase(word);break;
case '2': g<<t->search(word)<<'\n';break;
case '3': g<<t->prefix(word)<<'\n';break;
};
}
return 0;
}