Pagini recente » Cod sursa (job #2505586) | Cod sursa (job #1897674) | Cod sursa (job #537750) | Cod sursa (job #1641735) | Cod sursa (job #988509)
Cod sursa(job #988509)
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const char endCh = '\n';
class Trie {
Trie* child[26];
int words, childs;
public:
Trie() { words = 0; childs = 0; memset(child, 0, sizeof(child));}
void addWord(char *s);
bool deleteWord(char *s);
int countWord(char*);
int commonPrefix(char*, int);
};
int number(char s){ return s - 'a';}
void Trie::addWord(char *s) {
if(*s != endCh) {
if(child[number(*s)] == 0) {
childs++;
child[number(*s)] = new Trie;
}
child[number(*s)]->addWord(s + 1);
}
else words++;
}
bool Trie::deleteWord(char *s) {
if(*s == endCh) words--;
else if(child[number(*s)]->deleteWord(s + 1)) {
delete child[number(*s)];
child[number(*s)] = 0;
childs--;
}
if(words == 0 && childs == 0) return true;
return false;
}
int Trie::countWord(char *s) {
if(*s == endCh) return words;
if(child[number(*s)] == 0) return 0;
return child[number(*s)]->countWord(s + 1);
}
int Trie::commonPrefix(char *s, int depth) {
if(*s == endCh || child[number(*s)] == 0) return depth;
return child[number(*s)] -> commonPrefix(s + 1, depth + 1);
}
Trie T;
int main() {
char line[32];
fgets(line, 32, stdin);
while(!feof( stdin ) ) {
switch (line[0]) {
case '0': T.addWord(line + 2); break;
case '1': T.deleteWord(line + 2); break;
case '2': cout << T.countWord(line + 2) << "\n"; break;
case '3': cout << T.commonPrefix(line + 2, 0) << "\n"; break;
}
fgets(line, 32, stdin);
}
return 0;
}