Pagini recente » Cod sursa (job #2439967) | Cod sursa (job #3302212) | Cod sursa (job #456700) | Cod sursa (job #2925337) | Cod sursa (job #2313893)
#include<fstream>
#include<cstring>
using namespace std;
struct TRIE
{
char car;
int NrW,Pref,son,bro;
}Trie[5200026];
char word[25];
int DIM,o;
void Add ()
{
int root = 0, br = 0;
int leng = strlen (word);
for (int p = 1; p < leng; ++ p)
{
bool find = false;
for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
if (Trie[nod].car == word[p])
{
Trie[nod].Pref ++;
if (p == leng - 1)
{
Trie[nod].NrW ++;
return;
}
root = nod;
find = true;
break;
}
else br = nod;
if (find) continue;
Trie[++ DIM].car = word[p];
if (p == leng - 1) Trie[DIM].NrW = Trie[DIM].Pref = 1;
else Trie[DIM].NrW = 0, Trie[DIM].Pref = 1;
if (! Trie[root].son) Trie[root].son = DIM;
else Trie[br].bro = DIM;
root = DIM;
}
}
void Delete ()
{
int root = 0, leng = strlen (word);
for (int i = 1; i < leng; ++ i)
for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
if (Trie[nod].car == word[i])
{
Trie[nod].Pref --;
if (i == leng - 1) Trie[nod].NrW --;
root = nod;
break;
}
}
int Count_Word ()
{
int root = 0, leng = strlen (word);
bool ok = true;
for (int i = 1; i < leng && ok; ++ i)
{
ok = false;
for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
if (Trie[nod].car == word[i] && Trie[nod].Pref)
{
if (i == leng - 1) return Trie[nod].NrW;
root = nod;
ok = true;
break;
}
}
return 0;
}
int Max_Prefix ()
{
int res = 0, leng = strlen (word), root = 0;
bool ok = true;
for (int i = 1; i < leng && ok; ++ i)
{
ok = false;
for (int nod = Trie[root].son; nod; nod = Trie[nod].bro)
if (Trie[nod].car == word[i] && Trie[nod].Pref)
{
res ++;
root = nod, ok = true;
break;
}
}
return res;
}
int main()
{
ifstream f("trie.in");
ofstream g("trie.out");
while(f>>o)
{
f.getline(word,25);
if(!o)
Add();
else if(o==1)
Delete();
else if(o==2)
g<<Count_Word()<<'\n';
else
g<<Max_Prefix()<<'\n';
}
}