Pagini recente » Cod sursa (job #1546598) | Istoria paginii runda/cls11_round1 | Cod sursa (job #520966) | Cod sursa (job #2030144) | Cod sursa (job #2216217)
#include <bits/stdc++.h>
using namespace std;
struct Nod
{
Nod* fii[26];
int ap;
int g;
Nod()
{
for(int i = 0; i < 26; i++)
fii[i] = NULL;
ap = 0;
g = 0;
}
};
Nod* root = new Nod();
void trieInsert(Nod* root, const char* str)
{
if (str[0] == '\0')
root->ap++;
else
{
if (root->fii[str[0] - 'a'] == NULL)
{
root->fii[str[0] - 'a'] = new Nod();
root->g++;
}
trieInsert(root->fii[str[0] - 'a'], str + 1);
}
}
int trieFind(Nod* root, const char* str)
{
if (str[0] == '\0')
return root->ap;
else if (root->fii[str[0] - 'a'] == NULL)
return 0;
else
return trieFind(root->fii[str[0] - 'a'], str + 1);
}
bool trieErase(Nod* root, const char* str)
{
bool gd = 0;
if(str[0] == '\0')
root->ap--;
else
{
gd = trieErase(root->fii[str[0] - 'a'], str + 1);
if(gd == 1)
root->fii[str[0] - 'a'] = NULL;
}
if(gd)
root->g--;
if(root->g == 0 && root->ap == 0)
{
delete root;
root = NULL;
return 1;
}
else
return 0;
}
int trieMaxPrefix(Nod* root, const char* str, const int lg)
{
if(root->fii[str[0] - 'a'] == NULL)
return lg;
else
return trieMaxPrefix(root->fii[str[0] - 'a'], str + 1, lg + 1);
}
char lr[102];
int op;
string s;
int main()
{
ifstream fin ("trie.in");
ofstream fout ("trie.out");
while(fin.getline(lr, 102))
{
int sz = strlen(lr);
int op = 0;
string s = "";
op = lr[0] - '0';
for(int i = 2; i < sz; i++)
s += lr[i];
if(op == 0)
trieInsert(root, s.c_str());
else if(op == 1)
trieErase(root, s.c_str());
else if(op == 2)
fout << trieFind(root, s.c_str()) << "\n";
else
fout << trieMaxPrefix(root, s.c_str(), 0) << "\n";
}
return 0;
}