Pagini recente » Cod sursa (job #2789685) | Cod sursa (job #297446) | Cod sursa (job #1705103) | Cod sursa (job #2766662) | Cod sursa (job #3242320)
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <stack>
#include <string>
#include <vector>
#include <list>
#define nl '\n'
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int NMAX = 100001, SIGMA = 26, NODES_MAX = 115000;
struct node
{
list<pair<char, int>> childs;
unsigned short finished;
char childsNr;
int tata;
};
stack<int> st; /// stiva sa reutilizez
node trie[NODES_MAX];
int n = 1, i, op, sz, it, look, gogo;
string s;
int schFor(int wh, char elem)
{
for (auto& x : trie[wh].childs)
{
if (x.first == elem)
return x.second;
}
return 0;
}
int get_place()
{
if (st.empty())
return ++n;
else
{
op = st.top();
st.pop();
return op;
}
}
void add()
{
i = 1;
sz = s.size();
for (it = 0; it < sz; it++)
{
gogo = schFor(i, s[it]);
if (!gogo)
{
gogo = get_place();
trie[i].childs.push_back({s[it], gogo});
trie[i].childsNr++;
}
trie[gogo].tata = i;
i = gogo;
}
trie[i].finished++;
return;
}
void sterge()
{
i = 1;
sz = s.size();
for (it = 0; it < sz; it++)
{
gogo = schFor(i, s[it]);
i = gogo;
}
trie[i].finished--;
it--;
while (i != 1 && !trie[i].childsNr && !trie[i].finished)
{
gogo = schFor(trie[i].tata, s[it]);
trie[trie[i].tata].childsNr--;
trie[trie[i].tata].childs.remove({s[it], gogo});
st.push(i);
i = trie[i].tata;
it--;
}
return;
}
int countApp()
{
i = 1;
sz = s.size();
for (it = 0; it < sz; it++)
{
gogo = schFor(i, s[it]);
if (!gogo)
return 0;
i = gogo;
}
return trie[i].finished;
}
int longestPrefix()
{
i = 1;
sz = s.size();
op = 0;
for (it = 0; it < sz; it++)
{
gogo = schFor(i, s[it]);
if (!gogo)
return op;
i = gogo;
op++;
}
return op;
}
int main()
{
while (fin >> op)
{
fin >> s;
if (op == 0)
add();
else if (op == 1)
sterge();
else if (op == 2)
fout << countApp() << nl;
else if (op == 3)
fout << longestPrefix() << nl;
}
return 0;
}