Pagini recente » Cod sursa (job #406294) | Cod sursa (job #2102935) | Cod sursa (job #1949794) | Cod sursa (job #2911995) | Cod sursa (job #229310)
Cod sursa(job #229310)
#include <fstream>
#include <string>
using namespace std;
const int NrCar='z'-'a'+1;
class trie{
public:
int nr_words,nr_sons;
trie *leg[NrCar];
trie(){
nr_words=nr_sons=0;
memset(leg,0,sizeof(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<(int)word.length();++i){
if (!r->leg[word[i]-'a'])
r->leg[word[i]-'a']=new trie();
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<(int)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<(int)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;
for (i=0;i<(int)word.length();++i){
if (!r->leg[word[i]-'a']) return;
aux=r;
r=r->leg[word[i]-'a'];
r->nr_sons--;
if (aux->nr_sons==0) delete aux;
else
if (r->nr_sons==0) aux->leg[word[i]-'a']=0;
}
r->nr_words--;
if (r->nr_sons==0) delete r;
}
ifstream f("trie.in");
ofstream g("trie.out");
string s,word;
trie *t=new trie();
int main(){
t->nr_sons=1;
while (!f.eof()){
getline(f,s);
if (s.length()<3) continue;
word=s.substr(2,s.length()-2);
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;
}