题意:
度熊手上有一本神奇的字典,你可以在它里面做如下三个操作:
1、insert : 往神奇字典中插入一个单词
2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词
3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串
Input
这里仅有一组测试数据。第一行输入一个正整数N(1≤N≤100000)N(1≤N≤100000),代表度熊对于字典的操作次数,接下来NN行,每行包含两个字符串,中间中用空格隔开。第一个字符串代表了相关的操作(包括: insert, delete 或者 search)。第二个字符串代表了相关操作后指定的那个字符串,第二个字符串的长度不会超过30。第二个字符串仅由小写字母组成。
Output
对于每一个search 操作,如果在度熊的字典中存在给定的字符串为前缀的单词,则输出Yes 否则输出 No。
Sample Input
5 insert hello insert hehe search h delete he search hello
Sample Output
Yes No
思路:很开心,终于又遇到了中文题,题干还简洁明了~
这个题也不难,感觉是个很典型的字典树,就是加字符串,删含目标前缀的字符串,以及查找目标前缀是否粗存在
比较繁琐,又是加又是删,又是查的,不过一个套路,就是要加上一个计数的,因为是要删含目标前缀的所有字符串,所以,删的时候,找到目标前缀,后面的所有字符串全部删除,所以需要记录数目,更新含(目标前缀的前缀)的数量,所以加一个计数数组即可。
代码:(第一次自己写字典树的题,借鉴了题解,代码有点丑。。)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
int n,m,ans,num,kk[3000005];
int rt[3000005][33],x[33],l;
char ch[35],s[10];
int main()
{
scanf("%d",&n);
while(n--)
{
scanf("%s%s",s,ch);
if(s[0]=='i')
{
int root=0;
for(int i=0;i<strlen(ch);i++)
{
if(rt[root][ch[i]-'a'])
root=rt[root][ch[i]-'a'];
else {
rt[root][ch[i]-'a']=++num;
root=num;
}
kk[root]++;
}
}
else if(s[0]=='d')
{
l=0;
int root=0,ok=0,xx;
for(int i=0;i<strlen(ch);i++)
{
if(rt[root][ch[i]-'a'])
{
if(i==strlen(ch)-1)
{
if(rt[root][ch[i]-'a']==0) {ok=1;break;}
xx=rt[root][ch[i]-'a'];
rt[root][ch[i]-'a']=0;
root=xx;
}
else
root=rt[root][ch[i]-'a'];
}
else
{
ok=1;break;
}
x[++l]=root;
}
if(ok==0)
{
for(int i=1;i<=l;i++)
kk[x[i]]-=kk[xx];
}
}
else if(s[0]=='s')
{
int ok=0;
int root=0;
for(int i=0;i<strlen(ch);i++)
{
if(rt[root][ch[i]-'a'])
root=rt[root][ch[i]-'a'];
else {
ok=1;break;
}
if(kk[root]==0) ok=1;
}
if(ok) printf("No\n");
else printf("Yes\n");
}
}
}
/*
100
insert hello
insert hehe
i heh
d hehe
s hehe
s heh
s he
*/