Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
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
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
Sample Input
1 5 she he say shr her yasherhs
Sample Output
3
Source
简单的AC自动机(待解决)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 500010;
char str[1000010];
struct ACAutomaton{
int ch[maxn][26],fail[maxn],val[maxn],last[maxn],sz,root;
int newnode(){
memset(ch[sz],0,sizeof(ch[sz]));
val[sz] = 0;
return sz++;
}
void init(){
sz = 0;
root = newnode();
}
void insert(char *str){
int len = strlen(str);
int now = root;
for(int i = 0;i < len;i++){
int &tmp = ch[now][str[i]-'a'];
if(!tmp) tmp = newnode();
now = tmp;
}
val[now]++;
}
void getfail(){
queue<int> q;
fail[root] = root;
for(int i = 0;i < 26;i++){
int u = ch[root][i];
if(u){
fail[u] = last[u] = 0;
q.push(u);
}
}
while(!q.empty()){
int now = q.front();q.pop();
for(int i = 0;i < 26;i++){
int u = ch[now][i];
if(!u) ch[now][i] = ch[fail[now]][i];
else{
fail[u] = ch[fail[now]][i];
last[u] = val[fail[u]] ? fail[u]:last[fail[u]];
q.push(u);
}
}
}
}
int query(char *str){
int len = strlen(str);
int now = root;
int ret = 0;
for(int i = 0;i < len;i++){
now = ch[now][str[i]-'a'];
int tmp = now;
while(tmp != root && val[tmp]){
ret += val[tmp];
val[tmp] = 0;
tmp = last[tmp];
}
}
return ret;
}
}ac;
int main(){
int kase,n;
scanf("%d",&kase);
while(kase--){
ac.init();
scanf("%d",&n);
for(int i = 0;i < n;i++){
scanf("%s",str);
ac.insert(str);
}
ac.getfail();
scanf("%s",str);
printf("%d\n",ac.query(str));
}
return 0;
}