include stdio include stdlib include string struct Trie int prefix str

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Trie
{
int u, prefix;
struct Trie *parent, **arcs;
};
struct Trie* InitTrie()
{
struct Trie *peak=malloc(sizeof(struct Trie));
peak->arcs = malloc(26*sizeof(struct Trie*));
peak->u=0;
peak->prefix=0;
peak->parent=NULL;
return peak;
}
void Insert(struct Trie *Trie)
{
int i=0;
char *str=malloc(100000*sizeof(char));
scanf("%s", str);
//descend
struct Trie *El1,*El2;
for(El1=Trie; i < strlen(str); i++)
{
El2=El1->arcs[str[i]-97];
if(El2==0)
{
break;
}
El2->prefix++;
El1=El2;
}
//end
struct Trie *new;
for(; i < strlen(str); i++)
{
new=InitTrie();
El1->arcs[str[i]-97]=new;
new->parent=El1;
El1=new;
new->prefix++;
}
El1->u++;
if(El1->u>1)
{
for(El1->u=0;El1->parent!=NULL; El1=El1->parent)
{
El1->prefix--;
}
}
free(str);
}
void Delete(struct Trie *Trie)
{
int i=0;
char *str=malloc(100000*sizeof(char));
scanf("%s", str);
//descend
struct Trie *El1,*El2;
for(El1=Trie; i < strlen(str);i++)
{
El2=El1->arcs[str[i]-97];
if(El2==0)
{
break;
}
El2->prefix--;
El1=El2;
}
//end
free(str);
}
void Prefix(struct Trie *Trie)
{
int x=0,i=0;
char *str=malloc(100000*sizeof(char));
scanf("%s", str);
struct Trie *El1;
for(El1=Trie; i < strlen(str);i++)
{
if(El1->arcs[str[i]-97]==0)
{
x++;
break;
}
El1=El1->arcs[str[i]-97];
}
free(str);
if(x)
{
printf("%d\n",0);
}
else
{
printf("%d\n",El1->prefix);
}
}
int main (int argc, char const *argv[])
{
int n;
char cmd[7];
scanf("%d", &n );
struct Trie *trie=InitTrie();
for(; n > 0; n--)
{
scanf("%s", cmd);
if(cmd[0]=='I')
{
Insert(trie);
}
if(cmd[0]=='P')
{
Prefix(trie);
}
if(cmd[0]=='D')
{
Delete(trie);
}
}
return 0;
}