题目描述
原题来自:HDU 2222
给定 nn 个长度不超过 5050 的由小写英文字母组成的单词准备查询,以及一篇长为 mm 的文章,问:文中出现了多少个待查询的单词。多组数据。
输入格式
第一行一个整数 TT,表示数据组数;
对于每组数据,第一行一个整数 nn,接下去 nn 行表示 nn 个单词,最后一行输入一个字符串,表示文章。
输出格式
对于每组数据,输出一个数,表示文中出现了多少个待查询的单词。
样例
Inputcopy | Outputcopy |
---|---|
1 5 she he say shr her yasherhs | 3 |
数据范围与提示
对于全部数据,1\le n\le 10^4,1\le m\le 10^61≤n≤104,1≤m≤106。
#include<iostream>
#include<vector>
#include <cstring>
#include<algorithm>
using namespace std;
void get_next(char ch[],int l,int next[])
{
next[0]=-1;
int i=0,j=-1;
while(i<=l)
{
if(j==-1||ch[i]==ch[j])
next[++i]=++j;
else
j=next[j];
}
}
int num(int ll,int l,int next[],char a[],char b[])
{
int j=0;
for(int i=0;i<ll;i++)
{
while(b[i]!=a[j]&&j>0)
{
j=next[j];
}
if(b[i]==a[j])
{
j++;
}
if(j==l)
{
return 1;
j=next[j];
}
}
return 0;
}
struct st
{
char a[55];
} st[10004];
int main()
{
int n,m;
cin>>n;
char b[1000005];
int l,ll,next[10005];
while(n--)
{
cin>>m;
for(int i=0;i<m;i++)
{
cin>>st[i].a;
}
cin>>b;
int ans=0;
ll=strlen(b);
for(int i=0;i<m;i++)
{
l=strlen(st[i].a);
get_next(st[i].a,l,next);
ans+=num(ll,l,next,st[i].a,b);
}
cout<<ans<<endl;
}
}