Pagini recente » Cod sursa (job #1934355) | Cod sursa (job #200333) | Cod sursa (job #1901980) | Cod sursa (job #2195425) | Cod sursa (job #2123397)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie
{
int Nr,NrSons;
Trie * Son[26];
Trie()
{
Nr = NrSons = 0;
for(int i = 0; i < 26; ++i)
Son[i] = 0;
}
};
Trie * T = new Trie;
void Insert(Trie * p, char * Word)
{
if(Word[0] == 0)
{
p->Nr++;
return;
}
if(p->Son[Word[0]-'a'] == 0)
{
p->Son[Word[0]-'a'] = new Trie;
p->NrSons++;
}
Insert(p->Son[Word[0]-'a'],Word + 1);
}
int Search(Trie * p, char * Word)
{
if(Word[0] == 0)
return p->Nr;
if(p->Son[Word[0]-'a'] != 0)
return Search(p->Son[Word[0]-'a'],Word + 1);
return 0;
}
int Prefix(Trie * p, char * Word, int Level)
{
if(Word[0] == 0)
return Level;
if(p->Son[Word[0]-'a'] == 0)
return Level;
return Prefix(p->Son[Word[0]-'a'],Word + 1,Level+1);
}
int Delete(Trie * p, char * Word)
{
if(Word[0] == 0)
p->Nr--;
else
if(p->Son[Word[0]-'a'] != 0)
{
if(Delete(p->Son[Word[0]-'a'],Word + 1) == 1)
{
p->Son[Word[0]-'a'] = 0;
p->NrSons--;
}
}
if(p->Nr == 0 && p->NrSons == 0 && p != T)
{
delete p;
return 1;
}
return 0;
}
int main()
{
char Line[25];
while(fin.getline(Line,25))
{
if(Line[0] == '0')
Insert(T,Line+2);
if(Line[0] == '1')
Delete(T,Line+2);
if(Line[0] == '2')
fout << Search(T,Line+2) << "\n";
if(Line[0] == '3')
fout << Prefix(T,Line+2,0) << "\n";
}
return 0;
}