HDU 2222 Keywords Search

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
 
 
AC自动机模板
 
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct tree{
    int w,f;
    int t[26];
}t[1000001];
int tt,n,m,num=0;
char s[50],c[1000001];
queue <int> q;
inline void in(){
    int p=0,l;
    for (register int i=0;i<m;i++){
        l=s[i]-'a';
        if (!t[p].t[l]) t[p].t[l]=++num;
        p=t[p].t[l];
    }
    t[p].w++;
}
inline void mafa(){
    register int i;int k,p;
    q.push(0);t[0].f=0;
    while(!q.empty()){
        k=q.front();q.pop();
        for (i=0;i<26;i++)
        if (t[k].t[i]){
            p=t[k].f;
            while((!t[p].t[i])&&p) p=t[p].f;
            t[t[k].t[i]].f=(k==p)?0:t[p].t[i];
            //printf("%d %d %d %d %d
",i,k,p,t[t[k].t[i]].f,t[p].t[i]);
            q.push(t[k].t[i]);
        }
    }
}
inline void que(){
    register int i,j;
    int ans=0,k=strlen(c),p=0,x;
    for (i=0;i<k;i++){
        x=c[i]-'a';
        while(!t[p].t[x]&&p) p=t[p].f;
        //printf("%d %d %d
",i,p,ans);
        p=t[p].t[x];
        if (t[p].w) 
        for (j=p;j;j=t[j].f) ans+=t[j].w,t[j].w=0;
    }
    printf("%d
",ans);
}
int main(){
    register int i,j;
    scanf("%d",&tt);
    while(tt--){
        for (i=0;i<=num;i++)
        for (j=0;j<=26;j++)
        t[i].t[j]=0;
        for (i=0;i<=num;i++) t[i].w=t[i].f=0;
        num=0;
        scanf("%d",&n);
        for (i=1;i<=n;i++){
            scanf("%s",s);
            m=strlen(s);
            in();
        }
        mafa();
        scanf("%s",c);
        que();
    }
}
View Code
原文地址:https://www.cnblogs.com/Enceladus/p/5308687.html