Pagini recente » Cod sursa (job #1558863) | Cod sursa (job #857418) | Cod sursa (job #2367172) | Cod sursa (job #25604) | Cod sursa (job #2605278)
#include <bits/stdc++.h>
#define DAU ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
#define PLEC fin.close(); fout.close(); return 0;
using namespace std;
const string problem("trie");
ifstream fin(problem + ".in");
ofstream fout(problem + ".out");
class Trie {
public :
Trie() : cntsons(0), freq(0) {
memset(sons, 0, sizeof(sons));
}
inline void Add(const string& s, int 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, int 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 == 0 && sons[x] -> freq == 0) {
delete sons[x];
sons[x] = 0;
--cntsons;
}
}
inline int Count(const string& s, int ind = 0) {
int x = s[ind] - 'a';
if (sons[x]) {
if (ind == s.size() - 1)
return sons[x] -> freq;
else return sons[x] -> Count(s, ind + 1);
}
else return 0;
}
inline int LongestPrefix(const string& s, int ind = 0) {
int x = s[ind] - 'a';
if (sons[x] && ind < s.size())
return sons[x] -> LongestPrefix(s, ind + 1);
else return ind;
}
private:
int cntsons, freq;
Trie* sons[26];
};
Trie *root = new Trie;
int op;
string s;
int main() {
DAU
while (fin >> op >> s) {
if (op == 0)
root -> Add(s);
else if (op == 1)
root -> Erase(s);
else if (op == 2)
fout << root -> Count(s) << '\n';
else fout << root -> LongestPrefix(s) << '\n';
}
PLEC
}