[hdu2222] AC自动机 数组版

来源:互联网 发布:qq群发信息软件 编辑:程序博客网 时间:2024/06/06 00:24

Keywords Search

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

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

#include<iostream>#include<cstring>#include<cstdio>#include<queue>using namespace std;#define N 500005char s[N*2];int n,ans,T,sz;int fail[N],ch[N][30],value[N];bool vis[N];queue<int> q;void init(){    ans = sz = 0;    memset(fail,0,sizeof(fail)); memset(value,0,sizeof(value));    memset(ch,0,sizeof(ch)); memset(vis,0,sizeof(vis));}void insert(){    int len = strlen(s);int now = 0;    for( int i = 0; i < len; i++ ){        int x = s[i] - 'a';        if( !ch[now][x] ) ch[now][x] = ++sz;        now = ch[now][x];    }    ++value[now];}void fal(){    while( !q.empty() ) q.pop();    for( int i = 0; i < 26; i++ )        if( ch[0][i] ) q.push(ch[0][i]);    while( !q.empty() ){        int now = q.front(); q.pop();        for( int i = 0; i < 26; i++ ){            if( !ch[now][i] ){                ch[now][i] = ch[fail[now]][i];                continue;            }            fail[ch[now][i]] = ch[fail[now]][i];            q.push(ch[now][i]);        }    }}void ac(){    int len = strlen(s);int now = 0;    for( int i = 0;i < len; i++ ){        vis[now] = 1;        int x = s[i] - 'a';        int y = ch[now][x];        while( y && !vis[y] ){            vis[y] = 1;            ans += value[y];            y = fail[y];        }        now = ch[now][x];    }}int main(){    scanf("%d", &T);    while( T-- ){        init();        scanf("%d", &n);        while( n-- ){            scanf("%s", s);            insert();        }        scanf("%s", s);        fal();        ac();        printf("%d\n", ans);    }    return 0;}
0 0