hdu 2222 Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 71419 Accepted Submission(s): 24370
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
Recommend
lcy
Statistic | Submit | Discuss | Note
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
#define son_num 26
#define maxn 1000005
struct node
{
int terminal;
node *fail;
node *next[son_num];
node()
{
fail=NULL;
terminal=0;
memset(next,NULL,sizeof(next));
}
};
void insert(node *root,char *str)
{
node *p=root;
int i=0,index;
while(str[i])
{
index=str[i]-'a';
if(p->next[index]==NULL)
p->next[index]=new node();
p=p->next[index];
i++;
}
p->terminal++;
}
void build_fail(node *root)
{
queue<node*>que;
root->fail=NULL;
que.push(root);
while(!que.empty())
{
node *temp=que.front();
que.pop();
node *p=NULL;
for(int i=0; i<son_num; i++)
{
if(temp->next[i]!=NULL)
{
if(temp==root) temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL)
temp->next[i]->fail=root;
}
que.push(temp->next[i]);
}
}
}
}
int query(node *root,char *str)
{
int i=0,cnt=0,index,len;
len=strlen(str);
node *p=root;
while(str[i])
{
index=str[i]-'a';
while(p->next[index]==NULL&&p!=root)
p=p->fail;
p=p->next[index];
if(p==NULL) p=root;
node *temp=p;
while(temp!=root)
{
if(temp->terminal>=0)
{
cnt+=temp->terminal;
temp->terminal=-1;
}
else break;
temp=temp->fail;
}
i++;
}
return cnt;
}
int main()
{
int t,n;
char str[55];
char pattern[maxn];
scanf("%d",&t);
while(t--)
{
node *root=new node();
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%s",str);
insert(root,str);
}
build_fail(root);
scanf("%s",pattern);
bool flag=false;
int num=query(root,pattern);
printf("%d\n",num);
}
}