Pagini recente » Cod sursa (job #303005) | Monitorul de evaluare | Cod sursa (job #359) | Cod sursa (job #2687239) | Cod sursa (job #3298538)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie{
int cnt, nr_fii;
Trie *fiu[26];
Trie()
{
cnt = nr_fii = 0;
memset(fiu, 0, sizeof(fiu));
}
};
class TRIE{
public:
Trie *head = new Trie;
void Insert(Trie *nod, char *s)
{
if(*s == '\0')
{
nod->cnt++;
return ;
}
if(nod->fiu[*s - 'a'] == 0)
{
Trie *nod2 = new Trie;
nod->fiu[*s - 'a'] = nod2;
nod->nr_fii++;
}
Insert(nod->fiu[*s - 'a'], s + 1);
}
int Delete(Trie *nod, char *s)
{
if(*s == '\0')
nod->cnt--;
else if(Delete(nod->fiu[*s - 'a'], s + 1))
{
nod->nr_fii--;
nod->fiu[*s - 'a'] = 0;
}
if(nod->cnt == 0 && nod->nr_fii == 0 && nod != head)
{
delete nod;
return 1;
}
return 0;
}
int Query(Trie *nod, char *s)
{
if(*s == '\0')
return nod->cnt;
if(nod->fiu[*s - 'a'] == 0)
return 0;
return Query(nod->fiu[*s - 'a'], s + 1);
}
int Prefix(Trie *nod, char *s, int sol)
{
if(*s == '\0')
return sol;
if(nod->fiu[*s - 'a'] == 0)
return sol;
return Prefix(nod->fiu[*s - 'a'], s + 1, sol + 1);
}
};
int main()
{
TRIE T;
/// Problema Trie(Arhiva educationala)
int op;
char ch[25];
while(fin >> op >> ch)
{
switch(op)
{
case 0: T.Insert(T.head, ch);break;
case 1: T.Delete(T.head, ch);break;
case 2: fout << T.Query(T.head, ch) << "\n";break;
case 3: fout << T.Prefix(T.head, ch, 0) << "\n";break;
}
}
fout.close();
return 0;
}