Pagini recente » Monitorul de evaluare | Cod sursa (job #167029) | Istoria paginii runda/2232 | Monitorul de evaluare | Cod sursa (job #331344)
Cod sursa(job #331344)
#include<fstream>
#include<string>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
class Trie
{
private:
struct node
{
int nrw,nrp;
node *Next['z'-'a'+1];
node()
{
nrw=nrp=0;
memset(Next,0,sizeof(Next));
}
};
node rad;
public:
string word;
string ::iterator it;
int op;
void add(string word)
{
node *End=&rad;
End->nrp++;
for(it=word.begin();it!=word.end();it++)
{
if(End->Next[*it-'a']==0)
End->Next[*it-'a']=new node;
End=End->Next[*it-'a'];
End->nrp++;
}
End->nrw++;
}
void del(string word)
{
node *End=&rad,*Prev;
End->nrp--;
for(int i=0;i<(int)word.length();i++)
{
Prev=End;
End=End->Next[word[i]-'a'];
End->nrp--;
if(End->nrp==0)
{
Prev=Prev->Next[word[i]-'a']=0;
for(int j=i+1;j<(int)word.length();j++)
{
node *aux=End;
End=End->Next[word[j]-'a'];
delete aux;
}
delete End;
break;
}
}
if(Prev!=0)
End->nrw--;
}
int Search(string word)
{
node *End=&rad;
for(it=word.begin();it!=word.end();it++)
{
if(End->Next[*it-'a']==0)
return 0;
End=End->Next[*it-'a'];
}
return End->nrw;
}
int Pref(string word)
{
node *End=&rad;
for(it=word.begin();it!=word.end();it++)
{
if(End->Next[*it-'a']==0)
break;
End=End->Next[*it-'a'];
}
return it-word.begin();
}
};
Trie T;
int main()
{
while(f>>T.op)
{
f>>T.word;
if(T.op==0)
T.add(T.word);
if(T.op==1)
T.del(T.word);
if(T.op==2)
g<<T.Search(T.word)<<'\n';
if(T.op==3)
g<<T.Pref(T.word)<<'\n';
}
return 0;
}