(模板)hdoj1251(字典树模板题)
题目链接:https://vjudge.net/problem/HDU-1251
题意:给定一系列字符串之后,再给定一系列前缀,对每个前缀查询以该字符串为前缀的字符串个数。
思路:
今天开始学字典树,从入门题开始。用数组实现,count数组表示每个结点出现次数,trie[0]为根节点。插入和查询一个字符串的复杂度为O(len)。len为字符串的长度。
AC code:
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn=1e6+5; //树的大小,尽量开大点 int trie[maxn][30],num[maxn],cnt; char str[15]; void insert(char *s){ int len=strlen(s); int u=0; for(int i=0;i<len;++i){ int t=s[i]-'a'; if(!trie[u][t]){ ++cnt; memset(trie[cnt],0,sizeof(trie[cnt])); trie[u][t]=cnt; } u=trie[u][t]; ++num[u]; } } int query(char *s){ int len=strlen(s); int u=0; for(int i=0;i<len;++i){ int t=s[i]-'a'; if(!trie[u][t]) return 0; u=trie[u][t]; } return num[u]; } int main(){ cnt=0; memset(trie[0],0,sizeof(trie[0])); memset(num,0,sizeof(num)); while(gets(str),str[0]!='\0') insert(str); while(~scanf("%s",str)) printf("%d\n",query(str)); return 0; }
朋友们,无论这个世界变得怎样,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步