Pagini recente » Cod sursa (job #361081) | Cod sursa (job #1879216) | Cod sursa (job #1217533) | Cod sursa (job #2709562) | Cod sursa (job #1612958)
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
#define SIGMA 26
struct trie_nod{
int nr_ap, nr_pass;
trie_nod *copii[SIGMA];
trie_nod(){
nr_ap = 0;
nr_pass = 0;
for(int i = 0; i < SIGMA; ++i){
copii[i] = NULL;
}
}
trie_nod* add_child(const char ch){
const int x = ch - 'a';
if(copii[x] == NULL){
copii[x] = new trie_nod;
}
return copii[x];
}
trie_nod* get_child(const char ch)const{
return copii[ch-'a'];
}
};
void add_word(const char * str, trie_nod *n){
++n->nr_pass;
for( ; *str; ++str){
n = n->add_child(*str);
++n->nr_pass;
}
++n->nr_ap;
}
void remove_word(const char * str, trie_nod *n){
--n->nr_pass;
for( ; *str; ++str){
n = n->get_child(*str);
--n->nr_pass;
}
--n->nr_ap;
}
int nr_ap(const char * str, const trie_nod *n){
for( ; *str && n; ++str){
n = n->get_child(*str);
}
if(n){
return n->nr_ap;
}
return 0;
}
int lcp(const char * str, const trie_nod *n){
int rez = 0;
for( ; *str && n && n->nr_pass; ++str){
n = n->get_child(*str);
if(n && n->nr_pass){
++rez;
}
}
return rez;
}
int main()
{
ifstream f("trie.in");
ofstream g("trie.out");
int tip;
string str;
trie_nod *trie = new trie_nod;
trie->nr_pass = 1;
while((f >> tip) && (f >> str)){
if(tip == 0){
add_word(str.c_str(), trie);
}
else if(tip == 1){
remove_word(str.c_str(), trie);
}
else if(tip == 2){
g << nr_ap(str.c_str(), trie) << '\n';
}
else{
g << lcp(str.c_str(), trie) << '\n';
}
}
return 0;
}