Pagini recente » Cod sursa (job #1628907) | Monitorul de evaluare | Cod sursa (job #2239736) | Cod sursa (job #2445981) | Cod sursa (job #2017061)
#include <fstream>
using namespace std;
ifstream f ("trie.in");
ofstream g ("trie.out");
const int NMax=2000003;
const int sigma=27;
struct node
{
int pre;
int words;
int sons[sigma];
};
int S;
node T[NMax];
void insert_word(string str)
{
int node=0;
for(int i=0;i<str.size();++i)
{
int next=T[node].sons[str[i]-'a'];
if(next==0) T[node].sons[str[i]-'a']=++S;
node=T[node].sons[str[i]-'a'];
++T[node].pre;
}
++T[node].words;
}
void delete_word(string str)
{
int node=0;
for(int i=0;i<str.size();++i)
{
int next=T[node].sons[str[i]-'a'];
node=next;
--T[node].pre;
}
--T[node].words;
}
int words_query(string str)
{
int node=0;
for(int i=0;i<str.size();++i)
{
int next=T[node].sons[str[i]-'a'];
if(next==0) return 0;
node=next;
}
return T[node].words;
}
int pre_query(string str)
{
int node=0;
for(int i=0;i<str.size();++i)
{
int next=T[node].sons[str[i]-'a'];
node=next;
if(T[node].pre<=0) return i;
}
return str.size();
}
int main()
{
int x;
while(f>>x)
{
string cuv;
f>>cuv;
if(x==0) insert_word(cuv);
if(x==1) delete_word(cuv);
if(x==2) g<<words_query(cuv)<<'\n';
if(x==3) g<<pre_query(cuv)<<'\n';
}
return 0;
}