Pagini recente » Cod sursa (job #2949434) | Cod sursa (job #1055634) | Cod sursa (job #1888287) | Cod sursa (job #1969632) | Cod sursa (job #1164404)
#include <fstream>
using namespace std;
struct TRIE {
int cnt, nrFii;
TRIE *Son[26];
TRIE() {
cnt = nrFii = 0;
for(int i = 0; i < 26; i++)
Son[i] = NULL;
}
} *T;
int op;
string Word;
void Insert(TRIE *T, const string &S, int poz, int val) {
if(poz == S.length()) {
T->cnt += val;
return;
}
int ind = S[poz] - 'a';
if(!T->Son[ind]) {
T->Son[ind] = new TRIE;
T->nrFii++;
}
Insert(T->Son[ind], S, poz + 1, val);
if(!T->Son[ind]->cnt && !T->Son[ind]->nrFii) {
delete T->Son[ind];
T->Son[ind] = NULL;
T->nrFii--;
}
}
int Query(TRIE *T, const string &S, int poz) {
if(poz == S.length()) {
return T->cnt;
}
int ind = S[poz] - 'a';
if(!T->Son[ind]) return 0;
return Query(T->Son[ind], S, poz + 1);
}
int Prefix(TRIE *T, const string &S, int poz) {
if(poz == S.length() || !T->Son[ S[poz] - 'a' ])
return poz;
return Prefix(T->Son[ S[poz] - 'a' ], S, poz + 1);
}
int main() {
ifstream in("trie.in"); ofstream out("trie.out");
T = new TRIE;
while (in >> op >> Word) {
switch(op) {
case 0:
Insert(T, Word, 0, 1);
break;
case 1:
Insert(T, Word, 0, -1);
break;
case 2:
out << Query(T, Word, 0) << "\n";
break;
case 3:
out << Prefix(T, Word, 0) << "\n";
break;
}
}
}