Pagini recente » Cod sursa (job #506703) | Cod sursa (job #2416234) | Cod sursa (job #1739123) | Cod sursa (job #1294707) | Cod sursa (job #2738914)
#include <bits/stdc++.h>
using namespace std;
void DAU(const string &task = "") {
if (!task.empty())
freopen((task + ".in").c_str(), "r", stdin),
freopen((task + ".out").c_str(), "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
void PLEC() {
exit(0);
}
const int SIGMA(26);
class Trie {
public:
Trie() : cntsons(0), freq(0) {
memset(sons, 0, sizeof(sons));
}
inline void Query(const int& op, const string& s) {
if (op == 0)
Add(s);
else if (op == 1)
Erase(s);
else if (op == 2)
cout << Count(s) << '\n';
else if (op == 3)
cout << LongestPref(s) << '\n';
}
private:
inline void Add(const string& s, const size_t& ind = 0) {
int x = s[ind] - 'a';
if (!sons[x]) {
++cntsons;
sons[x] = new Trie;
}
if (ind == s.size() - 1)
++sons[x] -> freq;
else sons[x] -> Add(s, ind + 1);
}
inline void Erase(const string& s, const size_t& ind = 0) {
int x = s[ind] - 'a';
if (ind == s.size() - 1)
--sons[x] -> freq;
else sons[x] -> Erase(s, ind + 1);
if (sons[x] -> cntsons + sons[x] -> freq == 0) {
delete sons[x];
sons[x] = 0;
--cntsons;
}
}
inline int Count(const string& s, const size_t& ind = 0) const {
int x = s[ind] - 'a';
if (sons[x]) {
if (ind == s.size() - 1)
return sons[x] -> freq;
return sons[x] -> Count(s, ind + 1);
}
return 0;
}
inline int LongestPref(const string& s, const size_t& ind = 0) const {
int x = s[ind] - 'a';
if (sons[x] && ind < s.size())
return sons[x] -> LongestPref(s, ind + 1);
return ind;
}
int cntsons, freq;
Trie *sons[SIGMA];
};
Trie *root = new Trie;
int op;
string s;
signed main() {
DAU("trie");
while (cin >> op >> s)
root -> Query(op, s);
PLEC();
}