3、例题
Keywords Search [ HDU 2222 ]
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. (well, it‘s about time to exercise your English !)
输入格式
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.
输出格式
Print how many keywords are contained in the description.
输入样例
1
5
she
he
say
shr
her
yasherhs
输出样例
3
#include<cstdio>
#include<cstring>
#define MAXN 105
#define MAXM 1000005
struct Node
{
int next[30],x,fail,num,count;
};
Node tree[MAXM];
int n,tot,nowLen,root,t,q[MAXM];
char article[MAXM],word[MAXN];
void insert()
{
int temp,now=root,len=strlen(word);
for (int i=0;i<=len-1;i++)
{
temp=word[i]-‘a‘;
if (tree[now].next[temp]==0) { tot++; tree[now].next[temp]=tot; }
now=tree[now].next[temp];
}
tree[now].count++;
}
void getFail()
{
int head=1,tail=2;
q[1]=root;
while (head!=tail)
{
for (int i=0;i<=25;i++)
{
int next=tree[q[head]].next[i];
if (next!=0)
{
if (q[head]==root) tree[next].fail=root;
else
{
int temp=tree[q[head]].fail;
while (temp!=0)
{
if (tree[temp].next[i]!=0)
{
tree[next].fail=tree[temp].next[i];
break;
}
temp=tree[temp].fail;
}
if (temp==0) tree[next].fail=root;
}
q[tail++]=next;
}
}
head++;
}
}
int find()
{
int len=strlen(article),ans=0,n1=root;
for (int i=0;i<=len-1;i++)
{
int now=article[i]-‘a‘;
while (tree[n1].next[now]==0 && n1!=root) n1=tree[n1].fail;
n1=tree[n1].next[now];
if (n1==0) n1=root;
int n2=n1;
while (n2!=root && tree[n2].count!=-1)
{
ans+=tree[n2].count;
tree[n2].count=-1;
n2=tree[n2].fail;
}
}
return ans;
}
int main()
{
freopen("AC.in","r",stdin);
freopen("AC.out","w",stdout);
scanf("%d",&t);
for (int j=1;j<=t;j++)
{
scanf("%d",&n);
root=tot+1; tot++;
for (int i=1;i<=n;i++)
{
scanf("%s",word); nowLen=strlen(word)-1;
insert();
}
getFail(); for (int i=root+1;i<=tot;i++) if (tree[i].fail==0) tree[i].fail=root;
scanf("%s",article);
printf("%d\n",find());
}
return 0;
}
-----------------------------------------------------------------------------------------------------