您的位置:首页 > 其它

【hud2222】Keywords Search AC自动机

2016-02-24 14:50 246 查看

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


Source

AC自动机裸题…代码抄的大白

注意发现一个结束标记后,统计完答案就清零,因为要求的是出现了多少个串,而不是出现的总次数

数据范围坑爹,数组开大点…

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

const int SZ = 500010;

int val[SZ],ch[SZ][30],n = 0;

void insert(char s[])
{
int p = 0;
int l = strlen(s);
for(int i = 0;i < l;i ++)
{
int c = s[i] - 'a' + 1;
if(!ch[p][c]) ch[p][c] = ++ n;
p = ch[p][c];
}
val[p] ++;
}

int nxt[SZ],lst[SZ];

queue<int> q;

void build_ac()
{
nxt[0] = 0;
for(int i = 1;i <= 26;i ++)
{
int u = ch[0][i];
if(u)
{
nxt[u] = 0;
q.push(u);
lst[u] = 0;
}
}
while(q.size())
{
int f = q.front(); q.pop();
for(int i = 1;i <= 26;i ++)
{
int u = ch[f][i];
if(!u) continue;
q.push(u);
int v = nxt[f];
while(v && !ch[v][i]) v = nxt[v];
nxt[u] = ch[v][i];
lst[u] = val[nxt[u]] ? nxt[u] : lst[nxt[u]];
}
}
}

int dfs(int p)
{
int ans = val[p];
if(val[p]) val[p] = 0;
if(p)
ans += dfs(lst[p]);
return ans;
}

int find(char s[])
{
int l = strlen(s);
int p = 0;
int ans = 0;
for(int i = 0;i < l;i ++)
{
int c = s[i] - 'a' + 1;
while(p && !ch[p][c]) p = nxt[p];
p = ch[p][c];
if(val[p]) ans += dfs(p);
else if(lst[p]) ans += dfs(lst[p]);
}
return ans;
}

char s[SZ << 1];

void init()
{
memset(val,0,sizeof(val));
memset(ch,0,sizeof(ch));
n = 0;
memset(nxt,0,sizeof(nxt));
memset(lst,0,sizeof(lst));
}

int main()
{
int T;
scanf("%d",&T);
while(T --)
{
init();
int n;
scanf("%d",&n);
for(int i = 1;i <= n;i ++)
{
scanf("%s",s);
insert(s);
}
build_ac();
scanf("%s",s);
printf("%d\n",find(s));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: