Pagini recente » Cod sursa (job #824004) | Cod sursa (job #838821) | Cod sursa (job #2295137) | Cod sursa (job #714192) | Cod sursa (job #2579542)
#include<fstream>
#include<iostream>
using namespace std;
struct trie {
int nr_words, nr_sons;
trie* sons[26];
trie() {
nr_words = 0;
nr_sons = 0;
}
};
void add_word(trie* t, string &s, int pos) {
if (pos == (int) s.size()) {
t->nr_words++;
return;
}
int c = s[pos] - 'a';
if (t->sons[c] == 0) {
t->sons[c] = new trie();
t->nr_sons++;
}
add_word(t->sons[c], s, pos + 1);
}
int delete_word(trie* t, string &s, int pos, const trie* root) {
if (pos == (int) s.size()) {
t->nr_words--;
} else {
int c = s[pos] - 'a';
int is_total_delete = delete_word(t->sons[c], s, pos + 1, root);
if (is_total_delete == 1) {
t->sons[c] = 0;
t->nr_sons--;
}
}
if (t->nr_words == 0 && t->nr_sons == 0 && t != root) {
delete t;
return 1;
}
return 0;
}
int count_word(trie* t, string &s, int pos) {
if (pos == (int) s.size())
return t->nr_words;
int c = s[pos] - 'a';
if (t->sons[c] == 0)
return 0;
return count_word(t->sons[c], s, pos + 1);
}
int find_prefix(trie *t, string &s, int pos, int count) {
if (pos == (int) s.size()) {
return count;
}
int c = s[pos] - 'a';
if (t->sons[c] == 0) {
return count;
}
return find_prefix(t->sons[c], s, pos + 1, count + 1);
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
trie* t;
t = new trie();
while(true) {
int code; fin >> code;
string word; fin >> word;
if (fin.eof())
break;
if (code == 0) {
add_word(t, word, 0);
} else if (code == 1) {
delete_word(t, word, 0, t);
} else if (code == 2) {
fout << count_word(t, word, 0) << "\n";
} else if (code == 3) {
fout << find_prefix(t, word, 0, 0) << "\n";
}
}
return 0;
}