动态开点
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node
{
int val;
struct node *next[26];
}*head;
void Insert(char *s)
{
struct node *pp=head;
for(;*s;s++)
{
int id=*s-'a';
if(pp->next[id]==NULL)
{
pp->next[id]=(struct node*)malloc(sizeof(struct node));
pp->next[id]->val=0;
for(int i=0;i<26;i++)
pp->next[id]->next[i]=NULL;
}
pp=pp->next[id];
pp->val++;
}
}
int Search(char *s)
{
// struct node *pp=(struct node*)malloc(sizeof(struct node));
// pp=head; 不要重新申请内存,浪费内存 *******************************
struct node *pp=head;
for(;*s;s++)
{
int id=*s-'a';
if(pp->next[id]==NULL)
return 0;
pp=pp->next[id];
}
if(pp->val)
return 1;
return 0;
}
void DDDD(struct node *pp)
{
for(int i=0;i<26;i++)
{
if(pp->next[i]!=NULL)
DDDD(pp->next[i]);
pp->next[i]=NULL;
}
pp=NULL;
}
void Delete(char *s)
{
struct node *pp=head;
int num=0;
int len=strlen(s);
for(int i=0;i<len;i++)
{
int id=s[i]-'a';
if(pp->next[id]==NULL)
return;
pp=pp->next[id];
num=pp->val;
}
pp=head;
for(int i=0;i<len;i++)
{
int id=s[i]-'a';
pp=pp->next[id];
pp->val=pp->val-num;
}
DDDD(pp);
}
int main()
{
int n;
scanf("%d",&n);
head=(struct node*)malloc(sizeof(struct node));
head->val=0;
for(int i=0;i<26;i++)
head->next[i]=NULL;
while(n--)
{
char s1[10],s2[35];
scanf("%s%s",s1,s2);
if(s1[0]=='i')
Insert(s2);
else if(s1[0]=='s')
printf(Search(s2)?"Yes\n":"No\n");
else if(s1[0]=='d')
Delete(s2);
}
}
静态
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <map>
using namespace std;
const int N =1e5*26;
int ch[N][26],tot=1,cnt[N];
void Insert(char *s)
{
cnt[1]++;
for(int p=1;*s;s++)
{
int t=*s-'a';
cnt[p]++;
if(!ch[p][t])
{
ch[p][t]=++ tot;
}
cnt[p=ch[p][t]]++;
}
}
int Search(char *s)
{
int p=1;
while(*s&&p)
{
int t=*(s++)-'a';
if(cnt[p])
p=ch[p][t];
else
p=0;
}
return p;
}
void Delete(char *s)
{
int x=cnt[Search(s)];
if(!x) return;
int p = 1;
while(*s&&p)
{
int t=*(s++)-'a';
cnt[p]-=x;
if(cnt[ch[p][t]]==x)
{
ch[p][t]=0;
}
p=ch[p][t];
}
}
int main()
{
int n;
scanf("%d",&n);
char a[10],b[31];
for(int i=0;i<n;i++)
{
scanf("%s%s",a,b);
if(a[0]=='i')
Insert(b);
else if(a[0] == 'd')
Delete(b);
else
puts(Search(b)?"Yes":"No");
}
}