Pagini recente » Cod sursa (job #98729) | Cod sursa (job #443676) | Cod sursa (job #2201467) | Cod sursa (job #1891314) | Cod sursa (job #2169006)
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie{
trie *t[26] = {};
int cnt[26];
int total_cnt;
bool end_of_w;
trie()
{
end_of_w = false;
total_cnt = 0;
}
};
trie *t_node;
int convert_char_to_int(char c)
{
return int(c)-97;
}
void add_w(char *w)
{
int i=0;
trie *it = t_node;
while(i < strlen(w))
{
int poz = convert_char_to_int(w[i]);
if(it->t[poz] == NULL)
{
it->t[poz] = new trie;
}
it->cnt[poz]++;
it->total_cnt++;
it = it->t[poz];
i++;
}
it->end_of_w = true;
}
void delete_w(char *w,int i,trie*& it)
{
int poz = convert_char_to_int(w[i]);
trie *next_it = it->t[poz];
it->cnt[poz]--;
if(i+1 < strlen(w)) delete_w(w,i+1,next_it);
if(i == strlen(w)-1) it->t[poz]->end_of_w = false;
if(it->t[poz]->total_cnt == 0)
{
it->total_cnt--;
delete it->t[poz];
it->t[poz] = NULL;
}
}
int query_word(char *w,int i,trie* it)
{
int poz = convert_char_to_int(w[i]);
if(i == strlen(w)-1)
{
if(it->t[poz] != NULL)
{
if(it->t[poz]->end_of_w == true) return it->cnt[poz];
else return 0;
}
else return 0;
}
if(it->t[poz] != NULL)
{
if(i+1 < strlen(w)) query_word(w,i+1,it->t[poz]);
}
else return 0;
}
int query_prefix(char *w,int i,trie* it,int total)
{
int poz = convert_char_to_int(w[i]);
if(it->t[poz] != NULL)
{
//cout<<it->t[poz]<<" "<<poz<<"\n";
total++;
if(i+1 < strlen(w)) query_prefix(w,i+1,it->t[poz],total);
else return total;
}
else return total;
}
int main()
{
t_node = new trie;
int k1;
char cuv[21];
while(fin>>k1)
{
fin>>cuv;
if(k1 == 0)
{
add_w(cuv);
}
else if(k1 == 1)
{
delete_w(cuv,0,t_node);
}
else if(k1 == 2)
{
fout<<query_word(cuv,0,t_node)<<"\n";
}
else
{
fout<<query_prefix(cuv,0,t_node,0)<<"\n";
}
}
}