Pagini recente » Cod sursa (job #987887) | Cod sursa (job #1911340) | Cod sursa (job #2162333) | Cod sursa (job #2842192) | Cod sursa (job #3352727)
/*
*/
#include <fstream>
#include <vector>
#include <unordered_map>
class trie {
private:
struct nodd {
int cnt;
std::unordered_map<char,nodd*> nxt;
nodd() : cnt(0) {}
}*root;
bool erase(nodd *nod, const std::string &s, int idx) {
if(idx==(int)s.size()) {
if(nod->cnt>0) {
nod->cnt--;
}
return nod->cnt==0 && nod->nxt.empty();
}
if(nod->nxt.find(s[idx])==nod->nxt.end())
return 0;
if(erase(nod->nxt[s[idx]],s,idx+1)) {
delete nod->nxt[s[idx]];
nod->nxt.erase(s[idx]);
}
return nod->cnt==0 && nod->nxt.empty();
}
void clear(nodd *nod) {
for(const auto &it:nod->nxt) {
clear(it.second);
delete it.second;
}
}
public:
trie() {
root=new nodd;
}
~trie() {
clear(root);
delete root;
}
void insert(const std::string &s) {
nodd *nod=root;
for(int i=0; i<(int)s.size(); i++) {
if(nod->nxt.find(s[i])==nod->nxt.end()) {
nod->nxt[s[i]]=new nodd;
}
nod=nod->nxt[s[i]];
}
nod->cnt++;
}
int count(const std::string &s) {
nodd *nod=root;
for(int i=0; i<(int)s.size(); i++) {
if(nod->nxt.find(s[i])!=nod->nxt.end()) {
nod=nod->nxt[s[i]];
}
else {
return 0;
}
}
return nod->cnt;
}
int longest_prefix(const std::string &s) {
nodd *nod=root;
for(int i=0; i<(int)s.size(); i++) {
if(nod->nxt.find(s[i])!=nod->nxt.end()) {
nod=nod->nxt[s[i]];
}
else {
return i;
}
}
return (int)s.size();
}
void erase(const std::string &s) {
erase(root,s,0);
}
};
int main() {
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
std::string s;
int tip;
trie v;
while(fin >> tip >> s) {
if(tip==0) {
v.insert(s);
}
else if(tip==1) {
v.erase(s);
}
else if(tip==2) {
fout << v.count(s) << "\n";
}
else {
fout << v.longest_prefix(s) << "\n";
}
}
return 0;
}