Pagini recente » Cod sursa (job #2717307) | Cod sursa (job #564489) | Cod sursa (job #654538) | Cod sursa (job #3222670) | Cod sursa (job #3297993)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
const int lg=26;
struct trienode
{
struct trienode *children[lg];
int wordcnt;
trienode()
{
wordcnt=0;
for (int i=0; i<lg; i++)
children[i]=NULL;
}
};
trienode *root;
void insert_word (trienode *root, string word)
{
trienode *curr=root;
for (auto c:word)
{
int key=c-'a';
if (curr->children[c-'a']==NULL)
{
trienode *node=new trienode();
curr->children[key]=node;
}
curr=curr->children[key];
}
curr->wordcnt++;
}
bool isempty (trienode *nod)
{
for (int i=0; i<lg; i++)
if (nod->children[i])
return false;
return true;
}
trienode *delete_word (trienode *nod, string word, int i)
{
if (!nod)
return NULL;
if (i==word.size())
{
if (nod->wordcnt>0)
nod->wordcnt--;
if (isempty(nod))
{
delete(nod);
nod=NULL;
}
return nod;
}
int key=word[i]-'a';
nod->children[key]=delete_word(nod->children[key],word,i+1);
if (isempty(nod) && nod->wordcnt==0)
{
delete(nod);
nod=NULL;
}
return nod;
}
int frecv (trienode *root, string word)
{
trienode *curr=root;
for (auto c:word)
{
int key=c-'a';
if (curr->children[key]==NULL)
return 0;
curr=curr->children[key];
}
return curr->wordcnt;
}
int pref (trienode *root, string word)
{
trienode *curr=root;
int rez=0;
for (auto c:word)
{
int key=c-'a';
if (curr->children[key]==NULL)
return rez;
rez++;
curr=curr->children[key];
}
return rez;
}
int main()
{
root=new trienode();
int cer;
while (fin >> cer)
{
string s;
fin >> s;
if (cer==0)
insert_word(root,s);
if (cer==1)
delete_word(root,s,0);
if (cer==2)
fout << frecv(root,s) << '\n';
if (cer==3)
fout << pref(root,s) << '\n';
}
return 0;
}