hdu 2846 Repository 字典树的变形
Repository
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1129 Accepted Submission(s): 382
Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
Sample Input
20
ad
ae
af
ag
ah
ai
aj
ak
al
ads
add
ade
adf
adg
adh
adi
adj
adk
adl
aes
5
b
a
d
ad
s
Sample Output
0
20
11
11
2
/*hdu 2846 字典树的变形 2011.10.18*/
#include <iostream>
#include<cstring>
#define MAX 26
using namespace std;
typedef struct Trie_Node
{
int count; //记录包含该结点的单词个数
int id; //最后一次经过此结点的商品ID
Trie_Node *next[MAX];
}Trie;
void insert(Trie *root,char *s,int id)
{
Trie *p=root;
while(*s!='\0')
{
if(p->next[*s-'a']==NULL)
{
Trie *temp=(Trie *)malloc(sizeof(Trie));
for(int i=0;i<MAX;i++)
{
temp->next[i]=NULL;
}
temp->count=0;
temp->id=-1; //-1表示没有商品
p->next[*s-'a']=temp;
}
p=p->next[*s-'a'];
if(p->id!=id) //如果当前结点的商品ID不等于要插入商品的ID,则计数器count++,并且重新置ID的值
{
p->id=id;
p->count++;
}
s++;
}
}
int search(Trie *root,char *s)
{
Trie *p=root;
for(int i=0;s[i]!='\0';i++)
{
if(p->next[s[i]-'a']==NULL)
return 0;
p=p->next[s[i]-'a'];
}
return p->count;
}
int main(int argc, char *argv[])
{
int i,j;
int n,m;
char s[21];
Trie *root=(Trie *)malloc(sizeof(Trie));
for(i=0;i<MAX;i++)
{
root->next[i]=NULL;
}
root->count=0;
root->id=-1;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",s);
for(j=0;j<strlen(s);j++) //将字符串X=X1X2...Xn的分别以X1,X2...Xn开头的后缀字符串插入到Trie树中
{
insert(root,s+j,i);
}
}
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%s",s);
printf("%d\n",search(root,s));
}
return 0;
}
尝试过用KMP去解决,但是查找复杂度至少为0(p*(len1+len2)),试着提交了一下,严重超时。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?