Pagini recente » Cod sursa (job #2328851) | Cod sursa (job #604548) | Cod sursa (job #1500975) | Cod sursa (job #1905937) | Cod sursa (job #2553798)
#include <cstdio>
#define lettersNr 32
#define wordMax 32
using namespace std;
struct letter {
int ends=0;
letter*next[lettersNr];
};
letter*Tree;
int sol;
int code(char x) {
return x-'a';
}
char decode(int x) {
return (char)(x+'a');
}
void createTree() {
int i;
Tree=new letter;
for(i=0;i<lettersNr;++i) {
Tree->next[i]=NULL;
}
}
void add(char word[wordMax]) {
int i;
letter*L,*New;
for(L=Tree,i=0;word[i];++i) {
if(L->next[code(word[i])]!=NULL) {
L=L->next[code(word[i])];
}
else {
break;
}
}
for(;word[i];++i) {
New=new letter;
L->next[code(word[i])]=New;
L=L->next[code(word[i])];
}
++L->ends;
}
char use(letter*L,char besides) {
if(L->ends) {
return 1;
}
int i;
for(i=0;i<besides;++i) {
if(L->next[i]!=NULL) {
return 1;
}
}
for(i=besides+1;i<lettersNr;++i) {
if(L->next[i]!=NULL) {
return 1;
}
}
}
void sub(char word[wordMax]) {
int i;
letter*L,*D;
for(L=Tree,i=0;word[i];++i) {
L=L->next[code(word[i])];
}
--L->ends;
for(D=Tree->next[code(word[0])],L=D,i=1;word[i+1];++i) {
if(use(L,word[i])) {
D=L->next[code(word[i])];
}
L=L->next[code(word[i])];
}
if(use(L,-1)) {
return;
}
}
void howMany(char word[wordMax]) {
int i;
letter*L;
for(L=Tree,i=0;word[i];++i) {
L=L->next[code(word[i])];
}
printf("%d\n",L->ends);
}
void countEnds(letter*L) {
int i;
sol+=L->ends;
for(i=0;i<lettersNr;++i) {
if(L->next[i]!=NULL) {
countEnds(L->next[i]);
}
}
}
void prefLength(char word[wordMax]) {
int i;
letter*L;
for(L=Tree,i=0;word[i];++i) {
L=L->next[code(word[i])];
}
sol=0;
countEnds(L);
printf("%d\n",sol);
}
void formWord(char quest[wordMax],char word[wordMax]) {
int i;
for(i=2;quest[i];++i) {
word[i-2]=quest[i];
}
word[i-2]=quest[i];
}
void findCase(char q,char word[wordMax]) {
if(q-'0') {
if(q-'1') {
if(q-'2') {
prefLength(word);
}
else {
howMany(word);
}
}
else {
sub(word);
}
}
else {
add(word);
}
}
void play(char quest[wordMax]) {
char word[wordMax];
formWord(quest,word);
findCase(quest[0],word);
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
char quest[wordMax];
createTree();
for(gets(quest);quest[0];gets(quest)) {
play(quest);
}
return 0;
}