Pagini recente » Cod sursa (job #801385) | Cod sursa (job #377410) | Cod sursa (job #545733) | Cod sursa (job #765588) | Cod sursa (job #1165148)
#include <iostream>
#include <fstream>
#include <cstring>
#define sigma 26
using namespace std;
int op;
string s;
struct Trie {
int words, children;
Trie *son[sigma];
Trie() {
words = children = 0;
memset(son, 0, sizeof(son));
}
};
Trie *T = new Trie;
void add(Trie *nd, int p) {
if(p == int(s.size())) {
nd->words++;
return;
}
if(nd->son[int(s[p])-'a'] == NULL) {
nd->son[int(s[p])-'a'] = new Trie;
nd->children++;
}
add(nd->son[int(s[p])-'a'], p+1);
}
bool remove(Trie *nd, int p) {
if(p == int(s.size())) nd->words--;
else {
if(remove(nd->son[int(s[p])-'a'], p+1)) {
nd->son[int(s[p])-'a'] = NULL;
nd->children--;
}
}
if(nd->words == 0 && nd->children == 0 && nd != T) {
delete nd;
return true;
}
return false;
}
int count(Trie *nd, int p) {
if(p == int(s.size())) return nd->words;
if(nd->son[int(s[p])-'a'] == NULL) return 0;
return count(nd->son[int(s[p])-'a'], p+1);
}
int prefixes(Trie *nd, int p) {
if(p == int(s.size())) return p;
if(nd->son[int(s[p])-'a'] == NULL) return p;
return prefixes(nd->son[int(s[p])-'a'], p+1);
}
int main() {
ifstream f("trie.in");
ofstream g("trie.out");
while(!f.eof()) {
f>>op>>s;
if(f.eof()) break;
if(op == 0) add(T, 0);
if(op == 1) remove(T, 0);
if(op == 2) g<<count(T, 0)<<"\n";
if(op == 3) g<<prefixes(T, 0)<<"\n";
}
return 0;
}