Pagini recente » Cod sursa (job #1366772) | Cod sursa (job #40737) | Cod sursa (job #1281638) | Cod sursa (job #1638837) | Cod sursa (job #2613259)
#include <iostream>
#include <fstream>
#include <string>
#define LEN 26
#define CH word[index] - 'a'
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int task;
string word;
struct trie {
int cnt, cnt_fii;
trie *fiu[LEN];
trie() {
cnt = cnt_fii = 0;
for (int i = 0; i < LEN; i++)
fiu[i] = nullptr;
}
};
void ins(trie *nod, string word, int index) {
if (index == word.length()) {
nod->cnt++;
return;
}
if (nod->fiu[CH] == nullptr) {
nod->fiu[CH] = new trie;
nod->cnt_fii++;
}
ins(nod->fiu[CH], word, index + 1);
}
void del(trie *nod, string word, int index) {
if (index == word.length()) {
nod->cnt--;
return;
}
del(nod->fiu[CH], word, index + 1);
if (!nod->fiu[CH]->cnt && !nod->fiu[CH]->cnt_fii) { /// stergem fiul daca e nevoie
delete nod->fiu[CH];
nod->fiu[CH] = nullptr;
nod->cnt_fii--;
}
}
int occurencies(trie *nod, string word, int index) {
if (index == word.length())
return nod->cnt;
if (nod->fiu[CH] == nullptr)
return 0;
return occurencies(nod->fiu[CH], word, index + 1);
}
int longest_pref(trie *nod, string word, int index) {
if (index == word.length() || nod->fiu[CH] == nullptr)
return index;
return longest_pref(nod->fiu[CH], word, index + 1);
}
int main() {
trie *root = new trie;
while (fin >> task >> word) {
if (task == 0)
ins(root, word, 0);
else if (task == 1)
del(root, word, 0);
else if (task == 2)
fout << occurencies(root, word, 0) << '\n';
else
fout << longest_pref(root, word, 0) << '\n';
}
return 0;
}