Pagini recente » Cod sursa (job #2853095) | Cod sursa (job #2876220) | Cod sursa (job #27654) | Cod sursa (job #27676) | Cod sursa (job #2964727)
#include <fstream>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
const int NMAX = 100005, SIGMA = 26;
struct Trie
{
int freq, wordsInSubtree;
Trie* children[SIGMA];
Trie()
{
freq = wordsInSubtree = 0;
for(int i = 0; i < SIGMA; i++)
children[i] = NULL;
}
};
Trie* trie = new Trie();
void insert(Trie* root, char* s)
{
if(s[0] == '\0')
{
root->freq++;
return;
}
if(root->children[s[0]-'a'] == NULL)
{
root->children[s[0]-'a'] = new Trie();
root->wordsInSubtree++;
}
insert(root->children[s[0]-'a'], s + 1);
}
bool erase(Trie* root, char* s)
{
if(s[0] == '\0')
root->freq--;
else if(erase(root->children[s[0]-'a'], s + 1))
{
root->children[s[0]-'a'] = NULL;
root->wordsInSubtree--;
}
if(root->freq == 0 && root->wordsInSubtree == 0 && root != trie)
{
delete root;
return true;
}
return false;
}
int count(Trie* root, char* s)
{
if(s[0] == '\0')
return root->freq;
if(root->children[s[0]-'a'] == NULL)
return 0;
return count(root->children[s[0]-'a'], s + 1);
}
int lcp(Trie* root, char* s, int l = 0)
{
if(s[0] == '\0' || root->children[s[0]-'a'] == NULL)
return l;
return lcp(root->children[s[0]-'a'], s + 1, l + 1);
}
int main()
{
char* s = new char[101];
int op;
while(cin >> op >> s)
{
if(op == 0)
insert(trie, s);
else if(op == 1)
erase(trie, s);
else if(op == 2)
cout << count(trie, s) << '\n';
else
cout << lcp(trie, s) << '\n';
}
return 0;
}