Pagini recente » Cod sursa (job #1458651) | Cod sursa (job #481709) | Cod sursa (job #98250) | Cod sursa (job #2987291) | Cod sursa (job #581362)
Cod sursa(job #581362)
#include <fstream>
#include <string>
using namespace std;
struct Trie {
unsigned int wcnt, scnt;
Trie* sons[26];
Trie()
{
wcnt = scnt = 0;
for (unsigned short int i = 0; i < 26; i++) {
sons[i] = 0;
}
}
};
string mystr;
Trie* root = new Trie;
unsigned short int dec(const char chr)
{
return (unsigned short int) (chr - 'a');
}
void add(Trie* pobj, unsigned short int poz)
{
if (mystr[poz]) {
if (!(pobj->sons[dec(mystr[poz])])) {
pobj->sons[dec(mystr[poz])] = new Trie;
pobj->scnt++;
}
add(pobj->sons[dec(mystr[poz])], poz + 1);
} else {
pobj->wcnt++;
}
}
bool del(Trie* pobj, unsigned short int poz)
{
if (!mystr[poz]) {
pobj->wcnt--;
} else if (del(pobj->sons[dec(mystr[poz])], poz + 1)) {
pobj->scnt--;
pobj->sons[dec(mystr[poz])] = 0;
}
if (pobj != root && !(pobj->wcnt) && !(pobj->scnt)) {
delete pobj;
return 1;
} else {
return 0;
}
}
unsigned int count(Trie* pobj, unsigned short int poz)
{
if (mystr[poz]) {
return count(pobj->sons[dec(mystr[poz])], poz + 1);
} else {
return pobj->wcnt;
}
}
unsigned int pref(Trie* pobj, unsigned short int poz, unsigned int nr)
{
if (!mystr[poz] || !pobj->sons[dec(mystr[poz])]) {
return nr;
} else {
return pref(pobj->sons[dec(mystr[poz])] , poz + 1, nr + 1);
}
}
int main()
{
unsigned short int op;
ifstream fin("trie.in");
ofstream fout("trie.out");
while (fin.good()) {
fin >> op >> mystr;
switch (op) {
case 0:
add(root, 0);
break;
case 1:
del(root, 0);
break;
case 2:
fout << count(root, 0) << endl;
break;
case 3:
fout << pref(root, 0, 0) << endl;
break;
}
}
fin.close();
fout.close();
return 0;
}