Pagini recente » Cod sursa (job #894661) | Cod sursa (job #1670934) | Cod sursa (job #2886683) | Cod sursa (job #2044636) | Cod sursa (job #1698394)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Trie {
int num, numChildren;
vector<Trie*> children;
Trie(int a) {
num = 0;
numChildren = 0;
children.resize(26);
for(int i=0; i<26; ++i)
children[i] = NULL;
}
void add(string::iterator i, string::iterator j);
void remove(string::iterator i, string::iterator j);
int count(string::iterator i, string::iterator j);
int getMaxPrefLength(string::iterator i, string::iterator j);
};
void Trie::add(string::iterator i, string::iterator j) {
if(i == j) {
++num;
} else {
if(children[*i - 'a'] == NULL) {
children[*i - 'a'] = new Trie(0);
++numChildren;
}
children[*i - 'a'] -> add(i+1, j);
}
}
void Trie::remove(string::iterator i, string::iterator j) {
if(i == j) {
--num;
} else {
children[*i - 'a'] -> remove(i+1, j);
if(children[*i - 'a'] -> num == 0 && children[*i - 'a'] -> numChildren == 0) {
delete children[*i - 'a'];
children[*i - 'a'] = NULL;
--numChildren;
}
}
}
int Trie::count(string::iterator i, string::iterator j) {
if(i == j) {
return num;
} else {
if(children[*i - 'a'] != NULL) {
return children[*i - 'a'] -> count(i+1, j);
} else
return 0;
}
}
int Trie::getMaxPrefLength(string::iterator i, string::iterator j) {
if(children[*i - 'a'] != NULL && i != j) {
return children[*i -'a'] -> getMaxPrefLength(i+1, j) + 1;
} else
return 0;
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
int q;
string w;
Trie trie(0);
while(!fin.eof()) {
fin >> q >> w;
switch (q) {
case 0: {
trie.add(w.begin(), w.end());
break;
}
case 1: {
trie.remove(w.begin(), w.end());
break;
}
case 2: {
fout << trie.count(w.begin(), w.end()) << '\n';
break;
}
case 3: {
fout << trie.getMaxPrefLength(w.begin(), w.end()) << '\n';
break;
}
}
}
return 0;
}