现在有个字典要支持一下操作
1、insert : 往神奇字典中插入一个单词
2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词
3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串
字典树每个节点维护 sum[ i ]
delete 操作: 先查询包含该串的串个数 V, 该串的路径 每个点 - = V,
然后 memset(ch[u] ,0 ,sizeof (ch[u] ) )
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 | #include<iostream> #include <algorithm> #include <cstring> using namespace std; const int N=5e5+4; char word[80]; int len,sum[N]; int ch[N][30],tot=1; int find( char *s){ int i,u=1; len=strlen(s); for (i=0;i<len;i++){ int c=s[i]- 'a' ; if (ch[u][c]==0){ return 0; } u=ch[u][c]; } return sum[u]; } void insert( char *s){ int i,u=1; len=strlen(s); for (i=0;i<len;i++){ int c=s[i]- 'a' ; if (ch[u][c]==0){ ch[u][c]=++tot; } u=ch[u][c]; sum[u]++; } } void del( char *s, int v){ int i,u=1; len=strlen(s); for (i=0;i<len;i++){ int c=s[i]- 'a' ; if (ch[u][c]==0){ return ; } sum[u]-=v; u=ch[u][c]; } sum[u]=0; memset(ch[u],0, sizeof ch[u]); } int main(){ int t; scanf( "%d" ,&t); while (t--){ char op[10]; scanf( "%s%s" ,op,word); if (op[0]== 'i' ) insert(word); else if (op[0]== 'd' ) del(word,find(word)); else { if (find(word)) printf( "Yes\n" ); else printf( "No\n" ); } } return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!