Pagini recente » infoarena - comunitate informatica, concursuri de programare | Cod sursa (job #1085189) | Cod sursa (job #2330740) | Cod sursa (job #2035043) | Cod sursa (job #1135318)
#include<fstream>
#include<cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int op, len;
char c[40];
struct Trie{
int freq, words;
Trie *son[27];
Trie()
{
int i;
for (i = 0; i <= 26; ++i)
son[i] = NULL;
freq = words = 0;
}
};
Trie *T;
void Insert(Trie *nod)
{
int i, next;
for (i = 0; i<len; i++)
{
next = c[i] - 'a';
if (nod->son[next] == NULL)
nod->son[next] = new Trie;
nod = nod->son[next];
nod->freq++;
}
nod->words++;
}
void Delete(Trie *nod)
{
int i, next;
for (i = 0; i<len; i++)
{
next = c[i] - 'a';
nod = nod->son[next];
nod->freq--;
}
nod->words--;
}
int Search(Trie *nod)
{
int i, next;
for (i = 0; i<len; i++)
{
next = c[i] - 'a';
if (nod->son[next] == NULL)
return 0;
nod = nod->son[next];
}
return nod->words;
}
int Prefix(Trie *nod)
{
int i, next, sol = 0;
for (i = 0; i<len; i++)
{
next = c[i] - 'a';
if (nod->son[next] == NULL)
break;
nod = nod->son[next];
if (nod->freq>0) sol++;
else break;
}
return sol;
}
int main()
{
T = new Trie;
while (fin >> op >> c)
{
len = strlen(c);
switch (op)
{
case 0: Insert(T); break;
case 1: Delete(T); break;
case 2: fout << Search(T) << '\n'; break;
case 3: fout << Prefix(T) << '\n'; break;
}
}
return 0;
}