Pagini recente » Cod sursa (job #2750554) | Cod sursa (job #2084752) | Cod sursa (job #1374567) | Monitorul de evaluare | Cod sursa (job #2845679)
#include <fstream>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct Nod
{
int Nr, NrSons;
Nod * Son[26];
Nod()
{
Nr = NrSons = 0;
for(int i = 0; i < 26; ++i)
Son[i] = 0;
}
};
Nod * Trie = new Nod;
void Insert(char * S, Nod * p)
{
if(!(*S))
{
p->Nr++;
return;
}
int Index = *S - 'a';
if(!(p->Son[Index]))
{
p->Son[Index] = new Nod;
p->NrSons++;
}
Insert(S + 1, p->Son[Index]);
}
bool Delete(char * S, Nod * p)
{
if(!(*S)) p->Nr--;
else
{
int Index = *S - 'a';
if(Delete(S + 1, p->Son[Index]))
{
p->Son[Index] = 0;
p->NrSons--;
}
}
if(p->Nr == 0 && p->NrSons == 0 && p != Trie)
{
delete p;
return 1;
}
return 0;
}
int Print(char * S, Nod * p)
{
if(!(*S)) return p->Nr;
int Index = *S - 'a';
if(p->Son[Index])
return Print(S + 1, p->Son[Index]);
else return 0;
}
int Prefix(char * S, Nod * p, int k)
{
int Index = *S - 'a';
if(!(*S) || !(p->Son[Index])) return k;
else return Prefix(S + 1, p->Son[Index], k+1);;
}
int main()
{
char Line[25];
while(in.getline(Line, 25))
{
if(Line[0] == '0')
Insert(Line + 2, Trie);
else if(Line[0] == '1')
Delete(Line + 2, Trie);
else if(Line[0] == '2')
out << Print(Line + 2, Trie) << '\n';
else if(Line[0] == '3')
out << Prefix(Line + 2, Trie, 0) << '\n';
}
return 0;
}