Pagini recente » Cod sursa (job #586937) | Cod sursa (job #2167614) | Cod sursa (job #106594) | Cod sursa (job #869331) | Cod sursa (job #1344977)
#include <cstring>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct trie {
int f[26], cnt, nrf;
};
vector<trie> T;
ifstream in("trie.in");
ofstream out("trie.out");
void newnode() {
trie n;
n.cnt = n.nrf = 0;
memset(n.f, 0, sizeof(n.f));
T.push_back(n);
}
void ins(string s, int p, int node) {
if(p == s.size()) {
++T[node].cnt;
++T[node].nrf;
}
else {
if(T[node].f[s[p] - 'a'] == 0) {
newnode();
T[node].f[s[p] - 'a'] = T.size() - 1;
}
ins(s, p + 1, T[node].f[s[p] - 'a']);
++T[node].nrf;
}
}
void del(string s, int p, int node) {
if(p == s.size()) {
--T[node].cnt;
--T[node].nrf;
}
else {
if(T[node].f[s[p] - 'a'] == 0) {
newnode();
T[node].f[s[p] - 'a'] = T.size() - 1;
}
del(s, p + 1, T[node].f[s[p] - 'a']);
--T[node].nrf;
}
}
void print_no(string s, int p, int node) {
if(p == s.size())
out << T[node].cnt << '\n';
else if(T[node].f[s[p] - 'a'] == 0)
out << 0 << '\n';
else print_no(s, p + 1, T[node].f[s[p] - 'a']);
}
void print_LCP(string s, int p, int node, int sol) {
if(p == s.size() || T[node].f[s[p]-'a'] == 0 || T[T[node].f[s[p]-'a']].nrf == 0)
out << sol << '\n';
else
print_LCP(s, p + 1, T[node].f[s[p] - 'a'], sol + 1);
}
int main()
{
newnode();
newnode();
int op;
in >> op;
while(!in.eof()) {
string s;
in >> s;
if(op == 0)
ins(s, 0, 1);
if(op == 1)
del(s, 0, 1);
if(op == 2)
print_no(s, 0, 1);
if(op == 3)
print_LCP(s, 0, 1, 0);
in >> op;
}
return 0;
}