Pagini recente » Cod sursa (job #3283551) | Cod sursa (job #1092654) | Cod sursa (job #2821161) | Cod sursa (job #1322484) | Cod sursa (job #2338133)
#include <fstream>
#include <cstring>
#define lmax 30
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct tnode
{
tnode *ch[26];
int words;
int app;
tnode()
{
this->app = 0;
this->words = 0;
memset(this->ch, 0, sizeof(this->ch));
}
};
tnode *trie;
char p[lmax];
short qtype;
bool existsInTrie(tnode *t, char *s)
{
if (!(*s))
{
return (t->app!=0);
}
if (!t->ch[*s-'a'])
{
return false;
}
return existsInTrie(t->ch[*s-'a'],s+1);
}
void insertInTrie(tnode *t, char *s, bool exists)
{
if (!(*s))
{
++t->app;
if (!exists)
{
++t->words;
}
return;
}
if (!t->ch[*s-'a'])
{
t->ch[*s-'a'] = new tnode();
}
if (!exists)
{
++t->words;
}
insertInTrie(t->ch[*s-'a'], s+1, exists);
}
int cntApTrie(tnode *t, char *s)
{
if (!(*s))
{
return t->app;
}
return cntApTrie(t->ch[*s-'a'], s+1);
}
int largestPreff(tnode *t, char *s, int lg)
{
if (!(*s))
{
return lg;
}
if (!t->ch[*s-'a'])
{
return lg;
}
return largestPreff(t->ch[*s-'a'], s+1, lg+1);
}
bool deleteFromTrie(tnode *t, char *s)
{
if (!(*s))
{
--t->app;
if (!t->app)
{
--t->words;
}
if (!t->words)
{
return true;
}
return false;
}
bool wasD = deleteFromTrie(t->ch[*s-'a'], s+1);
if (wasD)
{
delete t->ch[*s-'a'];
t->ch[*s-'a'] = NULL;
--t->words;
}
if (!t->words)
{
return true;
}
return false;
}
int main()
{
trie = new tnode();
while (fin>>qtype>>p)
{
bool ex = existsInTrie(trie, p);
if (qtype == 0)
{
insertInTrie(trie, p, ex);
}
else if (qtype == 1)
{
if (!ex)
{
continue;
}
deleteFromTrie(trie, p);
}
else if (qtype == 2)
{
if (!ex)
{
fout<<0<<'\n';
continue;
}
fout<<cntApTrie(trie, p)<<'\n';
}
else
{
fout<<largestPreff(trie, p, 0)<<'\n';
}
}
fin.close();
fout.close();
return 0;
}