Pagini recente » Cod sursa (job #7878) | Cod sursa (job #2666470) | Cod sursa (job #425208) | Cod sursa (job #1806034) | Cod sursa (job #3241968)
#include <bits/stdc++.h>
using namespace std;
struct Nod
{
Nod(){
nr = 0;
for ( int i = 0 ; i < 30 ; i++ )
next[i] = NULL;
}
int nr;
Nod* next[30];
};
class Trie
{
Nod* root;
public:
Trie(){
root = new Nod();
}
void adauga(Nod* nod, string& s, int idx)
{
nod -> nr++;
if ( idx == s.size() )
return;
if ( nod -> next[s[idx] - 'a'] == NULL )
{
nod->next[s[idx]-'a'] = new Nod();
}
adauga(nod->next[s[idx]-'a'], s, idx+1);
}
void add(string s)
{
adauga(root, s, 0);
}
void afiseaza(Nod* nod, string s)
{
cout<<s<<" "<<nod -> nr<<'\n';
for ( char c = 'a' ; c <= 'z' ; c++ )
{
int nrc = c - 'a';
if ( nod -> next[nrc] != NULL )
{
afiseaza(nod -> next[nrc], s + c);
}
}
}
void afis()
{
afiseaza(root, "");
}
int del(Nod* nod, string& s, int idx)
{
nod -> nr--;
if ( idx == s.size() )
{
if ( nod -> nr == 0 )
{
delete nod;
return 1;
}
return 0;
}
if ( del(nod->next[s[idx]-'a'], s, idx+1) )
{
nod -> next[s[idx]-'a'] = NULL;
}
if ( nod -> nr == 0 )
{
delete nod;
return 1;
}
return 0;
}
void sterge(string s)
{
del(root, s, 0);
}
int nrap(Nod* nod, string& s, int idx)
{
if ( idx == s.size() )
{
int cate = 0;
for ( char c = 'a' ; c <= 'z' ; c++ )
{
if ( nod -> next[c-'a'] != NULL )
{
cate += nod -> next[c-'a'] -> nr;
}
}
return nod->nr - cate;
}
return nrap(nod->next[s[idx]-'a'], s, idx+1);
}
int nrap(string s)
{
return nrap(root, s, 0);
}
int maxp(Nod* nod, string& s, int idx)
{
if ( idx == s.size() )
{
return idx;
}
if ( nod -> next[s[idx] - 'a'] != NULL )
{
return maxp(nod -> next[s[idx] - 'a'], s, idx + 1);
}
else
{
return idx;
}
}
int max_pref(string s)
{
return maxp(root, s, 0);
}
};
ifstream in("trie.in");
ofstream out("trie.out");
int main()
{
Trie *t = new Trie();
int op;
string s;
while ( in>>op>>s )
{
if ( op == 0 )
{
t -> add(s);
}
else if ( op == 1 )
{
t -> sterge(s);
}
else if ( op == 2 )
{
out<<t->nrap(s)<<'\n';
}
else
{
out<<t->max_pref(s)<<'\n';
}
}
return 0;
}