Pagini recente » Cod sursa (job #1963875) | Cod sursa (job #721045) | Cod sursa (job #2839223) | Cod sursa (job #2595339) | Cod sursa (job #944376)
Cod sursa(job #944376)
#include <fstream>
#include <map>
using namespace std;
class Trie {
public:
Trie() {
root = new Node();
}
void insert( char * s ) {
Node * t = root;
for (int i = 0; ; ++i) {
++t->cnt_pre;
if (t->child[s[i]] == NULL) {
t->child[s[i]] = new Node;
}
t = t->child[s[i]];
if (s[i] == '\0') break;
}
++t->cnt_pre;
}
void remove( char * s ) { // s must be in trie
remove(s, root);
}
int count( char * s, bool whole = true ) {
Node * t = root;
for (int i = 0; ; ++i) {
if (s[i] == '\0' && whole == false) break;
if (t->child[s[i]] == NULL) return 0;
t = t->child[s[i]];
if (s[i] == '\0') break;
}
return t->cnt_pre;
}
int lenMatchPre( char * s ) {
Node * t = root;
for (int i = 0; ; ++i) {
if (s[i] == '\0') return i;
if (t->child[s[i]] == NULL) return i;
t = t->child[s[i]];
}
}
private:
struct Node {
Node() : cnt_pre(0) { }
map<char, Node *> child;
int cnt_pre;
};
Node * root;
void remove( char * s, Node * & t ) {
if (s[0] != '\0') {
remove( s+1, t->child[s[0]] );
}
--t->cnt_pre;
if (t->cnt_pre == 0 && t != root) {
delete t;
t = NULL;
}
}
};
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
Trie dict;
short op;
char s[30];
while (fin >> op) {
fin >> s;
switch (op) {
case 0: dict.insert(s); break;
case 1: dict.remove(s); break;
case 2: fout << dict.count(s) << '\n'; break;
case 3: fout << dict.lenMatchPre(s) << '\n'; break;
}
}
return 0;
}