Pagini recente » Cod sursa (job #2460202) | Cod sursa (job #1093981) | Cod sursa (job #1833194) | Cod sursa (job #42959) | Cod sursa (job #1674819)
#include <iostream>
#include <fstream>
#include <map>
#include <cstring>
using namespace std;
struct nod
{
int tr, fin;
nod*next[26];
nod(){
tr = 0;
fin = 0;
for(int i=0; i<26; i++) next[i] =0;
}
};
nod * root = new nod();
void add(string s)
{
nod *p = root;
for(int i=0; i<s.size(); i++)
{
if (p->next[s[i] - 'a'] == 0) p->next[s[i] - 'a'] = new nod();
p = p->next[s[i] - 'a'];
++p->tr;
}
++p->fin;
}
void del(string s)
{
nod *p = root;
for(int i=0; i<s.size(); i++)
{
if(p->next[s[i] - 'a']->tr == 1)
{
delete(p->next[s[i] - 'a']);
p->next[s[i] - 'a'] = 0;
return;
}
p = p->next[s[i] - 'a'];
--p->tr;
}
--p->fin;
}
int occ(string s)
{
nod *p = root;
for(int i=0; i<s.size(); i++)
{
if (p->next[s[i] - 'a'] == 0) return 0;
p = p->next[s[i] - 'a'];
}
return p->fin;
}
int prefix(string s)
{
nod *p = root;
for(int i=0; i<=s.size(); i++)
{
if (p->next[s[i] - 'a'] == 0) return i;
p = p->next[s[i] - 'a'];
}
return s.size();
}
int main()
{
ifstream f("trie.in");
ofstream g("trie.out");
int act;
string s;
while(f >> act >> s)
{
if (act == 0) add(s);
else
if (act == 1) del(s);
else
if (act == 2) g << occ(s) << "\n";
else
if (act == 3) g << prefix(s) << "\n";
}
// cout << root->next['a'];
f.close();
g.close();
return 0;
}