Pagini recente » Cod sursa (job #1354772) | Cod sursa (job #2042169) | Cod sursa (job #2143231) | Cod sursa (job #2482512) | Cod sursa (job #2018256)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream in ("trie.in");
ofstream out ("trie.out");
int const litmax = 26;
int const nmax = 20;
struct Trie {
int pref; //din cate cuvinte face parte prefixul pana in acest nod
Trie* vec[litmax];
};
Trie* root;
void addtrie(Trie* node, char* word) {
node->pref++;
//cout<<"A "<<node->pref<<" "<<word<<'\n';
if(*word != '\0') {
int pos = *word - 'a';
if(node->vec[pos] == NULL) //nullptr
node->vec[pos] = new Trie();
addtrie(node->vec[pos] , word + 1);
}
}
void deltrie(Trie* node , char* word) {
//cout<<"D "<<node->pref<<" "<<word<<'\n';
node->pref--;
//cout<<"D "<<node->pref<<" "<<word<<'\n';
if(*word != '\0') {
int pos = *word - 'a';
deltrie(node->vec[pos] , word + 1);
}
}
int aparitii(Trie* node , char* word) {
if(*word != '\0') {
int pos = *word - 'a';
if(node->vec[pos] == NULL)
return 0;
else
return aparitii(node->vec[pos] , word + 1);
} else {
int answer = node->pref;
for(int i = 0 ; i < litmax; i++) {
if(node->vec[i] != NULL) {
answer -= node->vec[i]->pref;
}
}
return answer;
}
}
int prefix(Trie* node, char* word, int lung = 0) {
//cout<<*word<<" "<<lung<<" "<<node->pref<<'\n';
if(*word != '\0' ) {
int pos = *word - 'a';
if(node->vec[pos] != NULL && 0 < node->vec[pos]->pref)
return prefix(node->vec[pos], word + 1, lung + 1);
}
return lung;
}
int main() {
char word[nmax + 4];
int option;
root = new Trie();
root->pref = 0;
while(in >> option && in >> word){
// cout<<option<<" "<<word<<" "<<strlen(word)<<'\n';
if(option == 0) {
addtrie(root, word);
} else if(option == 1) {
deltrie(root, word);
} else if(option == 2) {
out<<aparitii(root, word)<<'\n';
} else if(option == 3){
out<<prefix(root , word )<<'\n';
}
}
return 0;
}