Cod sursa(job #2572095)
Utilizator | Data | 5 martie 2020 11:39:13 | |
---|---|---|---|
Problema | Trie | Scor | 50 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.6 kb |
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie
{
int ap;
int val;
trie *son[26];
};
int a,l;
string s;
trie *root=new trie;
bool del(trie *where,int pos)
{
if (pos==l)
{
where->val--;
}
else
{
if (del(where->son[s[pos]-'a'],pos+1))
{
where->son[s[pos]-'a']=0;
}
}
where->ap--;
if (where->ap==0 && where!=root)
{
delete where;
return 1;
}
return 0;
}
int main()
{
while (fin>>a>>s)
{
if (a==0)
{
trie *where=root;
int i=0;
int sz=s.size()-1;
while (i<=sz)
{
if (where->son[s[i]-'a']==0)
{
where->son[s[i]-'a']=new trie;
where->son[s[i]-'a']->ap++;
if (i==sz)
where->son[s[i]-'a']->val++;
}
else
{
where->son[s[i]-'a']->ap++;
if (i==sz)
where->son[s[i]-'a']->val++;
}
where=where->son[s[i]-'a'];
i++;
}
}
if (a==1)
{
trie *where=root;
l=s.size();
del(where,0);
}
if (a==2)
{
trie *where=root;
int i=0;
int sz=s.size()-1;
int nr=0;
while (i<=sz)
{
if (where->son[s[i]-'a']==0)
i=sz+1;
else
{
if (i==sz)
nr=where->son[s[i]-'a']->val;
where=where->son[s[i]-'a'];
}
i++;
}
fout<<nr<<"\n";
}
if (a==3)
{
trie *where=root;
int i=0;
int sz=s.size()-1;
int nr=0;
while (i<=sz)
{
if (where->son[s[i]-'a']!=0)
{
if (where->son[s[i]-'a']->ap!=0)
{
nr++;
where=where->son[s[i]-'a'];
i++;
}
else
i=sz+1;
}
else
i=sz+1;
}
fout<<nr<<"\n";
}
}
return 0;
}