Pagini recente » Cod sursa (job #876674) | Sedinta 2008-10-10 | Cod sursa (job #236253) | Cod sursa (job #236258) | Cod sursa (job #3281550)
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct Trie
{
int nrCuv, nrAp;
Trie *fii[26];
Trie()
{
nrCuv = 0, nrAp = 0;
for (int i = 0; i < 26; i++)
{
fii[i] = nullptr;
}
}
void addWord(const string &str, unsigned int poz = 0)
{
int crtCh = str[poz] - 'a';
if (fii[crtCh] == nullptr)
{
fii[crtCh] = new Trie();
}
fii[crtCh]->nrAp++;
if (poz == str.size() - 1)
{
fii[crtCh]->nrCuv++;
}
else
fii[crtCh]->addWord(str, poz + 1);
}
void deleteWord(const string &str, unsigned int poz = 0)
{
int crtCh = str[poz] - 'a';
fii[crtCh]->nrAp--;
if (poz == str.size() - 1) // trebuie sa ne oprim cu totul
{
fii[crtCh]->nrCuv--;
if (fii[crtCh]->nrAp == 0) // nu mai este niciun motiv sa tinem nodul
{
delete fii[crtCh];
fii[crtCh] = nullptr;
}
return;
}
fii[crtCh]->deleteWord(str, poz + 1); // stergem in continuare
if (fii[crtCh]->nrAp == 0)
{
delete fii[crtCh]; // dealocam memoria in cazul in care nu mai e nevoie de ea
fii[crtCh] = nullptr;
}
}
int countAp(const string &str, unsigned int poz = 0)
{
int crtCh = str[poz] - 'a';
if (poz == str.size() - 1)
return fii[crtCh]->nrCuv;
return fii[crtCh]->countAp(str, poz + 1);
}
int longestCommonPrefix(const string &str, unsigned int poz = 0)
{
int crtCh = str[poz] - 'a';
if (fii[crtCh] == nullptr)
{
return 0;
}
if (poz == str.size() - 1)
{
return 1;
}
return 1 + fii[crtCh]->longestCommonPrefix(str, poz + 1);
}
};
int main()
{
int op;
string str;
Trie T;
while (f >> op >> str)
{
switch (op)
{
case 0:
T.addWord(str);
break;
case 1:
T.deleteWord(str);
break;
case 2:
g << T.countAp(str) << '\n';
break;
case 3:
g << T.longestCommonPrefix(str) << '\n';
}
}
return 0;
}