Pagini recente » Cod sursa (job #2393248) | Cod sursa (job #3261854) | Cod sursa (job #173578) | Cod sursa (job #3161295) | Cod sursa (job #3297997)
#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;
}
bool delete_word (trienode *nod, string word, int i)
{
if (nod==NULL)
return false;
if (i==word.size())
{
if (nod->wordcnt>0)
nod->wordcnt--;
return isempty(nod) && nod->wordcnt==0;
}
int key=word[i]-'a';
if (nod->children[key]==NULL)
return false;
bool ok=delete_word(nod->children[key],word,i+1);
if (ok)
{
delete nod->children[key];
nod->children[key]=NULL;
return isempty(nod) && nod->wordcnt==0;
}
return false;
}
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;
}