• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
hyxzc
博客园    首页    新随笔    联系   管理    订阅  订阅

C++之路进阶——hdu2222(Keywords Search)

/*
Keywords Search

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 47794 Accepted Submission(s): 15228


Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.

Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.

Output
Print how many keywords are contained in the description.

Sample Input
1
5
she
he
say
shr
her
yasherhs

Sample Output
3
*/

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 
 8 char s[51],m[1000001];
 9 int T,n,sz,ans;
10 int a[500001][27]/*字典树*/ ,q[500001],point[500001],danger[500001]/*单词结束标志*/;
11 bool mark[500001];
12 
13 int ins()
14 {
15 int now=1,l=strlen(s);
16 for (int i=0;i<l;i++)
17 {
18 int t=s[i]-'a'+1;
19 if (a[now][t]) now=a[now][t];
20 else now=a[now][t]=++sz; 
21 }    
22 danger[now]++;    
23 }
24 
25 int acmach()
26 {
27 q[0]=1;point[1]=0;
28 int now,w=1,t=0;
29 while (t<w)
30 {
31 now=q[t++];    
32 for (int i=1;i<=26;i++)    
33 { 
34 if (!a[now][i]) continue;
35 int k=point[now];
36 while (!a[k][i]) k=point[k];
37 point[a[now][i]]=a[k][i];
38 q[w++]=a[now][i];
39 }
40 }
41 }
42 
43 int solve()
44 {
45 int k=1,l=strlen(m);
46 for(int i=0;i<l;i++)
47 {
48 mark[k]=1;
49 int t=m[i]-'a'+1;
50 while(!a[k][t]) k=point[k];
51 k=a[k][t];
52 if(!mark[k])
53 for(int j=k;j;j=point[j])
54 {
55 ans+=danger[j];
56 danger[j]=0;
57 }
58 }
59 printf("%d\n",ans);
60 }
61 
62 int main()
63 {
64 scanf("%d",&T);
65 while(T--)
66 {
67 ans=0;
68 sz=1;
69 scanf("%d",&n);
70 for(int i=1;i<=26;i++)a[0][i]=1;
71 for (int i=0;i<n;i++)
72 {
73 scanf("%s",s);
74 ins();
75 } 
76 scanf("%s",m);    
77 acmach();
78 solve();
79 for(int i=1;i<=sz;i++)
80 {
81 point[i]=danger[i]=mark[i]=0;
82 for(int j=1;j<=26;j++)
83 a[i][j]=0;
84 }
85 }
86 }

 

posted @ 2016-01-21 17:10  hyxzc  阅读(276)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3