Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 42877 Accepted Submission(s): 13502
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
Author
Wiskey
题意:给你n个单词,再给你一个字符串,求单词在 所给字符串出现的个数。
题解:建一颗字典树,从所给字符串的每一个位置当成首字符查找,若找到单词则删掉这个单词。
(注:这题很多用AC自动机写的,字典树可能会超时,用C++交,如果超时,再交几发)
#include<cstring> #include<cstdio> #include<algorithm> #include<iostream> #include<cmath> #include<vector> #include<cstring> #define N 1000010 using namespace std; int n; char s[N]; struct Tire { int num; struct Tire *net[26]; Tire() { num=0; for(int i=0; i<26; i++) { net[i]=NULL; } } }; void CreatTire(Tire *p,char s[]) { int i=0; Tire *q=p; while(s[i]) { int nx=s[i]-'a'; if(q->net[nx]==NULL) { q->net[nx]=new Tire; } q=q->net[nx]; i++; } q->num++; } int Serch(Tire *p,char s[],int ii) { int i=ii; Tire *q=p; int res=0; while(s[i]) { int nx=s[i]-'a'; if(q->net[nx]==NULL)break; if(q->net[nx]->num) { res+=q->net[nx]->num; q->net[nx]->num=0; } q=q->net[nx]; i++; } return res; } void Delete(Tire *p) { if(p==NULL)return; for(int i=0; i<26; i++) { Delete(p->net[i]); } free(p); } int main() { //freopen("test.in","r",stdin); int t; cin>>t; while(t--) { scanf("%d",&n); Tire *p=new Tire; for(int i=0; i<n; i++) { scanf("%s",s); CreatTire(p,s); } scanf("%s",s); int ans=0; for(int i=0; s[i]; i++) { ans+=Serch(p,s,i); } printf("%d\n",ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。