Pagini recente » Cod sursa (job #2999356) | Cod sursa (job #1218925) | Cod sursa (job #173951) | Cod sursa (job #314488) | Cod sursa (job #2758285)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node
{
Node *next[26];
int word_count;
int app_count;
Node()
{
for (int i =0; i<26; i++) next[i] = NULL;
word_count = 0;
app_count = 0;
}
};
string s;
int op;
Node *root;
void adauga_in_trie(Node *current, string word, int poz)
{
current->app_count++;
if(poz==word.size())
{
current->word_count++;
return;
}
if(current->next[word[poz]-'a']==NULL) current->next[word[poz]-'a']= new Node();
adauga_in_trie(current->next[word[poz]-'a'],word,poz+1);
}
void sterge_din_trie(Node *current, string word, int poz)
{
current->app_count--;
if(poz==word.size())
{
current->word_count--;
return;
}
sterge_din_trie(current->next[word[poz]-'a'],word,poz+1);
if(current->next[word[poz]-'a']->app_count == 0)
{
delete current->next[word[poz]-'a'];
current->next[word[poz]-'a']=NULL;
}
}
int aparitii(Node *current, string word, int poz)
{
if(poz==word.size()) return current->word_count;
if(current->next[word[poz]-'a']!=NULL)
return aparitii(current->next[word[poz]-'a'], word, poz+1);
return 0;
}
int prefix(Node *current, string word, int poz)
{
if(poz==word.size()) return word.size();
if(current->next[word[poz]-'a']!=NULL)
return prefix(current->next[word[poz]-'a'], word, poz+1);
return poz;
}
int main()
{
root=new Node();
while(fin>>op>>s)
{
if(op==0)
{
adauga_in_trie(root,s,0);
}
if(op==1)
{
sterge_din_trie(root,s,0);
}
if(op==2)
{
fout<<aparitii(root,s,0)<<"\n";
}
if(op==3)
{
fout<<prefix(root,s,0)<<"\n";
}
}
return 0;
}