Pagini recente » Cod sursa (job #664976) | Cod sursa (job #2814030) | Clasament simulareoji2015p2 | Cod sursa (job #2669059) | Cod sursa (job #1092122)
#include<cstdio>
using namespace std;
const int MAXALPHA=28;
const int MAXW=23;
struct node
{
int ap,no_sons;
node* next[MAXALPHA];
node()
{
no_sons=ap=0;
for (int i=0; i<MAXALPHA; ++i)
next[i]=NULL;
}
};
node* root=new node();
int opt;
char w[MAXW];
bool should_del;
void add(node* curr, char* s)
{
if (!s[0])
++curr->ap;
else
{
int letter=s[0]-'a'+1;
if (curr->next[letter]==NULL)
{
++curr->no_sons;
curr->next[letter]=new node();
}
add(curr->next[letter],s+1);
}
}
bool del(node* curr, char* s)
{
if (!s[0])
--curr->ap;
else
{
int letter=s[0]-'a'+1;
if (del(curr->next[letter],s+1))
{
curr->next[letter]=0;
--curr->no_sons;
}
}
//daca trebuie sa sterg nodul curent
if (!curr->no_sons && !curr->ap && curr!=root)
{
delete curr;
return true;
}
else
return false;
}
int print(node* curr, char* s)
{
if (!s[0])
return curr->ap;
else
{
int letter=s[0]-'a'+1;
if (curr->next[letter])
return print(curr->next[letter],s+1);
else
return 0;
}
}
int prefix(node* curr, char* s,int lg)
{
int letter=0;
if (s[0])
letter=s[0]-'a'+1;
if (!s[0] || !curr->next[letter])
return lg;
else
return prefix(curr->next[letter],s+1,lg+1);
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
while (scanf("%d%s",&opt,w)!=EOF)
{
if (opt==0)
add(root,w);
else if (opt==1)
del(root,w);
else if (opt==2)
printf("%d\n",print(root,w));
else if (opt==3)
printf("%d\n",prefix(root,w,0));
}
return 0;
}