Pagini recente » Cod sursa (job #1453) | Monitorul de evaluare | Cod sursa (job #57331) | Profil pestcontrol606 | Cod sursa (job #482852)
Cod sursa(job #482852)
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct trie {
trie* son[26];
int count, numSon;
trie() {
count = 0;
numSon = 0;
memset(son, 0, 26*sizeof(trie*));
}
};
int countWord(const trie* T, const string& word, int pos) {
if (pos == word.size()) {
return T->count;
} else if (T->son[word[pos] - 'a']) {
return countWord(T->son[word[pos] - 'a'], word, pos + 1);
} else return -pos;
}
void insertWord(trie* T, const string& word, int pos)
{
if (pos == word.size()) {
T->count++;
} else {
int c = word[pos] - 'a';
if (!T->son[c]) {
T->numSon++;
T->son[c] = new trie;
}
insertWord(T->son[c], word, pos + 1);
}
}
int removeWord(trie* T, const string& word, int pos)
{
if (pos == word.size()) {
T->count--;
if (T->count == 0 && T->numSon == 0) {
delete T;
return 1;
} else return 0;
} else {
int c = word[pos] - 'a';
if (T->son[c]) {
if (removeWord(T->son[c], word, pos+1)) {
T->son[c] = 0;
T->numSon--;
if (T->count == 0 && T->numSon == 0 && pos != 0) {
delete T;
return 1;
} else return 0;
} else return 0;
} else return 1;
}
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
int op;
string word;
trie* T = new trie;
int res;
while (!fin.eof()) {
fin >> op >> word;
// cout << op << " " << word << endl;
switch (op) {
case 0: insertWord(T, word, 0); break;
case 1: removeWord(T, word, 0); break;
case 3: res = countWord(T, word, 0);
res = res <= 0 ? -res : word.size();
fout << res << endl; break;
case 2:
res = countWord(T, word, 0);
res = res <= 0 ? 0 : res;
fout << res << endl; break;
default: cout << 'x' << endl;
}
}
return 0;
}