Pagini recente » Cod sursa (job #1642269) | Cod sursa (job #1312379) | Cod sursa (job #391158) | Cod sursa (job #524931) | Cod sursa (job #2544726)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int SIGMA = 26;
const int MAX_LEN = 20;
class Trie
{
public:
Trie *sons[SIGMA];
int nrap, nrc;
Trie()
{
for(int i = 0; i < SIGMA; i++)
sons[i] = NULL;
nrap = nrc = 0;
}
};
Trie *root = new Trie();
int type;
char word[MAX_LEN + 5];
Trie* Insert(Trie* node, char *s)
{
node-> nrap++;
if(s[0] == '\0')
node-> nrc++;
else
{
if(node-> sons[s[0] - 'a'] == NULL)
node-> sons[s[0] - 'a'] = new Trie();
node-> sons[s[0] - 'a'] = Insert(node-> sons[s[0] - 'a'], s + 1);
}
return node;
}
Trie* Delete(Trie* node, char *s)
{
node-> nrap--;
if(s[0] == '\0')
node-> nrc--;
else
node-> sons[s[0] - 'a'] = Delete(node-> sons[s[0] - 'a'], s + 1);
if(node-> nrap == 0)
node = NULL;
return node;
}
int NrAp(Trie* node, char *s)
{
if(s[0] == '\0')
return node-> nrc;
if(node-> sons[s[0] - 'a'] == NULL)
return 0;
return NrAp(node-> sons[s[0] - 'a'], s + 1);
}
int BestPref(Trie* node, char *s)
{
if(s[0] == '\0')
return 0;
if(node-> sons[s[0] - 'a'] != NULL)
return 1 + BestPref(node-> sons[s[0] - 'a'], s + 1);
return 0;
}
int main()
{
while(fin >> type)
{
fin >> word;
if(type == 0)
root = Insert(root, word);
else if(type == 1)
root = Delete(root, word);
else if(type == 2)
fout << NrAp(root, word) << '\n';
else
fout << BestPref(root, word) << '\n';
}
return 0;
}