Pagini recente » Cod sursa (job #604091) | Cod sursa (job #178499) | Cod sursa (job #2016894) | Cod sursa (job #2975984) | Cod sursa (job #2453995)
#include <bits/stdc++.h>
#define lmax 25
using namespace std;
class trie
{
private:
#define uint unsigned int
#define endWord(w) (!(*w))
static const uint alphabetSize = 26;
class trieNode
{
private:
int cnt = 0, oth = 0;
trieNode *f[alphabetSize];
public:
trieNode()
{
memset(f, 0, sizeof(f));
}
void ins(char *c)
{
if (endWord(c))
{
++cnt;
return;
}
if (!f[*c - 'a'])
{
f[*c - 'a'] = new trieNode();
++oth;
}
f[*c - 'a']->ins(c+1);
}
int getCnt(char *c)
{
if (endWord(c))
return cnt;
if (!f[*c - 'a'])
return 0;
return f[*c-'a']->getCnt(c+1);
}
bool rem(char *c)
{
if (endWord(c))
{
--cnt;
if (!cnt && !oth) return true;
return false;
}
if (f[*c-'a']->rem(c+1))
{
delete f[*c-'a'];
f[*c-'a'] = 0;
--oth;
if (!cnt && !oth) return true;
}
return false;
}
int largestPref(char *c)
{
if (endWord(c) || !f[*c-'a'])
return 0;
return 1 + f[*c-'a']->largestPref(c+1);
}
void remAll()
{
if (!oth && !cnt)
return;
for (uint tr = 0; tr < alphabetSize; ++tr)
{
if (!f[tr])
continue;
f[tr]->remAll();
}
}
};
public:
trieNode *root;
trie()
{
root = new trieNode();
}
void addWordApp(char *w)
{
root->ins(w);
}
int countWordApp(char *w)
{
return root->getCnt(w);
}
void removeWordApp(char *w)
{
root->rem(w);
}
int getLargestWordPref(char *w)
{
return root->largestPref(w);
}
void clearTrie()
{
root->remAll();
}
};
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
trie t;
char s[lmax];
int op;
while(cin>>op)
{
scanf("%s", s);
switch(op)
{
case 0:
t.addWordApp(s);
break;
case 1:
t.removeWordApp(s);
break;
case 2:
printf("%d\n", t.countWordApp(s));
break;
case 3:
printf("%d\n", t.getLargestWordPref(s));
break;
}
}
fclose(stdin);
fclose(stdout);
return 0;
}