Pagini recente » Cod sursa (job #1063201) | Cod sursa (job #1289974) | Cod sursa (job #2098409) | Cod sursa (job #3176775) | Cod sursa (job #2906744)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
struct Nod
{
int fr; /// de cate ori apare un cuvant
int fr_pre; /// de cate ori apare prefixul
Nod *leg[26];
Nod ()
{
fr = 0;
fr_pre = 0;
for (int i = 0; i < 26; i++)
leg[i] = NULL;
}
};
class Trie
{
protected:
Nod *root;
public:
Trie()
{
root = new Nod;
}
void Add (string w)
{
Nod *aux = root;
aux -> fr_pre++;
for (int i = 0; w[i]; i++)
{
if (aux -> leg[w[i] - 'a'] == NULL)
{
Nod *q;
q = new Nod;
aux -> leg[w[i] - 'a'] = q;
}
aux = aux -> leg[w[i] - 'a'];
aux -> fr_pre++;
}
aux -> fr++;
}
void Erase (string w)
{
Nod * aux = root;
aux -> fr_pre--;
for (int i = 0; w[i]; i++)
{
aux = aux -> leg[w[i] - 'a'];
aux -> fr_pre--;
}
aux -> fr--;
}
int NrAparitii (string w)
{
Nod *aux = root;
for (int i = 0; w[i]; i++)
{
if (aux -> leg[w[i] - 'a'] == NULL || aux -> fr_pre == 0)
return 0;
aux = aux -> leg[w[i] - 'a'];
}
return aux -> fr;
}
int LongestPref (string w)
{
Nod *aux = root;
int ans = 0;
for ( ;w[ans]; ans++)
{
if (aux -> fr_pre == 0)
return ans - 1;
if (aux -> leg[w[ans] - 'a'] == NULL)
return ans;
aux = aux -> leg[w[ans] - 'a'];
}
return ans;
}
};
Trie T;
int main()
{
int task;
string s;
while (fin >> task >> s)
{
if (task == 0)
T.Add(s);
else if (task == 1)
T.Erase(s);
else if (task == 2)
fout << T.NrAparitii(s) << "\n";
else fout << T.LongestPref(s) << "\n";
}
return 0;
}