Pagini recente » Cod sursa (job #1215861) | Cod sursa (job #2486347) | Cod sursa (job #286068) | Cod sursa (job #2976764) | Cod sursa (job #2921183)
#include <fstream>
using namespace std;
const int SIGMA = 26;
struct Trie {
Trie *sons[SIGMA];
int freq;
int words;
Trie() {
freq = 0;
words = 0;
for (int i = 0; i < SIGMA; i++) {
sons[i] = NULL;
}
}
};
void ins(Trie *&root, char *S) {
if (*S == '\0') {
root->freq++;
root->words++;
} else {
if (root->sons[S[0] - 'a'] == NULL) {
root->sons[S[0] - 'a'] = new Trie();
}
root->sons[S[0] - 'a']->freq++;
ins(root->sons[S[0] - 'a'], S + 1);
}
}
void del(Trie *&root, char *S) {
if (*S == '\0') {
if (root->freq > 0) {
root->freq--;
root->words--;
}
} else {
if (root->sons[S[0] - 'a'] != NULL) {
root->sons[S[0] - 'a']->freq--;
del(root->sons[S[0] - 'a'], S + 1);
}
}
}
int cntocc(Trie *&root, char *S) {
if (*S == '\0') {
return root->words;
} else {
if (root->sons[S[0] - 'a'] == NULL || root->sons[S[0] - 'a']->freq == 0) {
return 0;
}
return cntocc(root->sons[S[0] - 'a'], S + 1);
}
}
int maxpref(Trie *&root, char *S, int cnt = 0) {
if (*S == '\0') {
return cnt;
} else {
if (root->sons[S[0] - 'a'] != NULL && root->sons[S[0] - 'a']->freq != 0) {
return maxpref(root->sons[S[0] - 'a'], S + 1, cnt + 1);
} else {
return cnt;
}
}
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
int t;
Trie *root = new Trie();
while (fin >> t) {
char* S = new char[20 + 1];
fin >> S;
if (t == 0) {
ins(root, S);
} else if (t == 1) {
del(root, S);
} else if (t == 2) {
fout << cntocc(root, S) << "\n";
} else {
fout << maxpref(root, S) << "\n";
}
}
return 0;
}