Pagini recente » Cod sursa (job #3123071) | Stalpisori | Cod sursa (job #3227506) | Cod sursa (job #2851776) | Cod sursa (job #2561645)
#include <iostream>
#include <fstream>
using namespace std;
const int SIGMA = 26;
ifstream f("trie.in");
ofstream g("trie.out");
int cmd;
string s;
bool del;
struct node{
int uses=0;
int words=0;
struct node* nodes[SIGMA];
node() {for(int i=0;i<SIGMA;++i) nodes[i] = NULL;}
};
void add_word(struct node *node,int ind)
{
int letter;
///increase the uses of the letter
node->uses++;
///stop condition
if(ind == s.size()) {node->words++;return;}
///get next node,create if needed
letter = s[ind]-'a';
if(node->nodes[letter] == NULL)
{
struct node *new_node = new struct node;
node->nodes[letter] = new_node;
}
///next letter
add_word(node->nodes[letter],ind+1);
}
void remove_word(struct node *node,int ind)
{
int letter;
if(ind < s.size())
{
letter = s[ind]-'a';
remove_word(node->nodes[letter],ind+1);
if(del==1) node->nodes[letter] = NULL;
}
else node->words--;
node->uses--;
if(node->uses == 0) free(node), del=1;
else del=0;
}
int word_frequency(struct node *node,int ind)
{
int letter;
///stop condition
if(ind == s.size()) return node->words;
///next letter
letter = s[ind]-'a';
if(node->nodes[letter] == NULL) return 0;
return word_frequency(node->nodes[letter],ind+1);
}
int common_prefix(struct node *node,int ind)
{
int letter;
///stop condition
if(ind == s.size()) return ind;
///next letter
letter = s[ind]-'a';
if(node->nodes[letter] == NULL) return ind;
return common_prefix(node->nodes[letter],ind+1);
}
void print_trie(struct node* node,int ind)
{
char letter;
if(ind==-1) cout<<"ROOT ";
else
{
letter = 'a'+ind;
cout<<letter<<' '<<node->uses<<' '<<node->words;
}
cout<<'\n';
for(int i=0;i<SIGMA;++i) if(node->nodes[i] != NULL) print_trie(node->nodes[i],i);
}
int main()
{
struct node *root = new struct node;
root->uses = 100005;
while(f>>cmd)
{
f>>s; del=0;
if(cmd == 0) add_word(root,0);
if(cmd == 1) remove_word(root,0);
if(cmd == 2) g<<word_frequency(root,0)<<'\n';
if(cmd == 3) g<<common_prefix(root,0)<<'\n';
//print_trie(root,-1); cout<<'\n';
}
return 0;
}