Pagini recente » Cod sursa (job #6677) | Cod sursa (job #1206782) | Cod sursa (job #1309136) | Cod sursa (job #6752) | Cod sursa (job #1218444)
#include <iostream>
#include <fstream>
#include <map>
#include <string.h>
#include <string>
#include <algorithm>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
string s;
int n;
class trie
{
public:
int x,y;
trie* ch[26];
trie();
};
trie::trie()
{
x=0;
y=0;
memset(ch,0,sizeof(ch));
}
void add (int x, trie *t)
{
if (x==n) { t->x++; t->y++; return;}
t->x++;
if (t->ch[s[x]-'a']==NULL)
{
t->ch[s[x]-'a'] = new trie();
}
add(x+1,t->ch[s[x]-'a']);
}
void del(int x, trie *t)
{
if (x==n) { t->x--; t->y--; return;}
t->x--;
del(x+1,t->ch[s[x]-'a']);
if ((t->ch[s[x]-'a'])->x==0)
{
t->ch[s[x]-'a'] = NULL;
}
}
int rez=0;
void counter(int x, trie *t)
{
if (x==n) {rez = t->y; return;}
if (t->ch[s[x]-'a']==NULL)
{
rez=0;
return;
} else counter(x+1,t->ch[s[x]-'a']);
}
void prefix(int x, trie *t)
{
if (x==n) {rez = n; return;}
if (t->ch[s[x]-'a']==NULL)
{
rez=x;
return;
} else prefix(x+1,t->ch[s[x]-'a']);
}
trie *root;
int main()
{
root = new trie();
while (!fin.eof())
{
int x=-1;
fin>>x;
fin>>s;
n = s.length();
if (x==-1) break;
if (x==0)
{
add(0,root);
} else if (x==1)
{
del(0,root);
} else if (x==2)
{
counter(0,root);
fout<<rez<<'\n';
} else
{
prefix(0,root);
fout<<rez<<'\n';
}
}
return 0;
}