Pagini recente » Cod sursa (job #1327324) | Cod sursa (job #2633065) | Cod sursa (job #3271904) | Cod sursa (job #2031704) | Cod sursa (job #3303742)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
const int lg=26;
struct trie
{
struct trie *children[lg];
int cnt, endw;
trie()
{
cnt=endw=0;
for (int i=0; i<lg; i++)
children[i]=NULL;
}
};
trie *root;
void insert_word (trie *root, string word)
{
trie *curr=root;
for (auto c:word)
{
int key=c-'a';
if (curr->children[key]==NULL)
curr->children[key]=new trie();
curr=curr->children[key];
curr->cnt++;
}
curr->endw++;
}
void delete_word (trie *root, string word)
{
trie *curr=root;
for (auto c:word)
{
int key=c-'a';
curr=curr->children[key];
curr->cnt--;
}
curr->endw--;
}
int frecv (trie *root, string word)
{
trie *curr=root;
for (auto c:word)
{
int key=c-'a';
if (curr->children[key]==NULL)
return 0;
curr=curr->children[key];
}
return curr->endw;
}
int pref (trie *root, string word)
{
trie *curr=root;
int rez=0;
for (auto c:word)
{
int key=c-'a';
if (curr->children[key]==NULL || curr->children[key]->cnt==0)
return rez;
rez++;
curr=curr->children[key];
}
return rez;
}
int main()
{
root=new trie();
int cer;
while (fin >> cer)
{
string s;
fin >> s;
if (cer==0)
insert_word(root,s);
if (cer==1)
delete_word(root,s);
if (cer==2)
fout << frecv(root,s) << '\n';
if (cer==3)
fout << pref(root,s) << '\n';
}
return 0;
}