Pagini recente » Cod sursa (job #2288460) | Cod sursa (job #3236371) | Cod sursa (job #3183011) | Cod sursa (job #1338841) | Cod sursa (job #1328103)
#include <fstream>
#include <string>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node
{
int N;
Node* sons[27];
Node()
{
N = 0;
for(int i =0;i<=26;i++)
sons[i] = NULL;
}
} ;
void update(string s, int pos, Node * x)
{
if(pos == s.length())
{
x->N ++;
return;
}
int y = s[pos] - 'a';
if(x->sons[s[pos]-'a'] != NULL)
{
update(s, pos+1, x->sons[s[pos]-'a']);
return;
}
x->sons[s[pos]-'a'] = new Node();
update(s, pos+1, x->sons[s[pos]-'a']);
}
bool del(string s, int pos, Node *x)
{
if(pos == s.length())
{
if(x->N == 1)
{
x->N --;
return true;
}
return false;
}
if(x->sons[s[pos]-'a'] == NULL)
return false;
bool res = del(s, pos+1, x->sons[s[pos]-'a']);
if(res)
{
x->sons[s[pos]-'a'] = NULL;
delete x->sons[s[pos]-'a'];
//return true;
}
return false;
}
int queryAp(string s, int pos, Node* x)
{
if(pos == s.length())
return x->N;
if(x->sons[s[pos]-'a'] == NULL)
return 0;
return queryAp(s, pos+1, x->sons[s[pos]-'a']);
}
int queryCMLP(string s, int pos, Node* x)
{
if(x->sons[s[pos]-'a']!=NULL)
return 1 + queryCMLP(s, pos+1, x->sons[s[pos]-'a']);
return 0;
}
int main()
{
int op;
string s;
Node * T = new Node();
while(fin>>op)
{
fin>>s;
if(op == 0)
update(s,0,T);
else if(op == 1)
del(s,0,T);
else if(op == 2)
fout<<queryAp(s,0,T)<<'\n';
else fout<<queryCMLP(s,0,T)<<'\n';
}
fin.close();
fout.close();
return 0;
}