Pagini recente » Cod sursa (job #1594885) | Cod sursa (job #2894025) | Cod sursa (job #1434041) | Cod sursa (job #2009007) | Cod sursa (job #228975)
Cod sursa(job #228975)
#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_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,*p[NMAX];
for (i=0;i<word.length();++i){
r=r->leg[word[i]-'a'];
p[i]=r;}
r->nr_words--;
for (i--;i>0;i--)
if (p[i]->nr_sons > 0 || p[i]->nr_words>0) return;
else {delete p[i];p[i-1]->nr_sons--;p[i-1]->leg[word[i]-'a']=0;}
}
ifstream f("trie.in");
ofstream g("trie.out");
string s,word;
//trie t,*r=new trie();
int main(){
//t=*r;
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;
}