标签:a long uil nbsp with 文章 main else should span
指针我一般都会出错,所以还是自己写数组版本。
InputFirst 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.
OutputPrint how many keywords are contained in the description.Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=1000010;
int Next[maxn][26],End[maxn],fail[maxn];
int cnt,root=1,ans;//root不能为0
void _init()
{
memset(Next,0,sizeof(Next));
memset(End,0,sizeof(End));
memset(fail,0,sizeof(fail));
ans=0;cnt=1;
}
void _insert(char s[])
{
int L=strlen(s);
int now=root;
for(int i=0;i<L;i++){
if(!Next[now][s[i]-‘a‘]) Next[now][s[i]-‘a‘]=++cnt;
now=Next[now][s[i]-‘a‘];
}
End[now]++;
}
void _build()//bfs
{
queue<int>q;
q.push(root);
while(!q.empty()){
int Now=q.front();q.pop();
for(int i=0;i<26;i++){
if(Next[Now][i]){
if(Now==root) fail[Next[Now][i]]=root;
else{
int p=fail[Now];
while(p){//给儿子们找对象
if(Next[p][i]){
fail[Next[Now][i]]=Next[p][i];
break;//找到了就停止
}
p=fail[p];
}
if(!p) fail[Next[Now][i]]=root;//不晓得?
}
q.push(Next[Now][i]);
}
}
}
}
void _query(char s[])
{
int L=strlen(s);
int Now=root;
for(int i=0;i<L;i++){
int x=s[i]-‘a‘;
while(Now!=root&&!Next[Now][x]) Now=fail[Now];
Now=Next[Now][x];
if(!Now) Now=root;//不晓得?
int tmp=Now;
while(tmp!=root){
if(End[tmp]>=0){
ans+=End[tmp];
End[tmp]=-1;//避免重复
}
else break;
tmp=fail[tmp];
}
}
}
int main()
{
char s[55];
char c[maxn] ;
int n,j,i,T;
scanf("%d",&T);
while(T--){
_init();
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%s",s);
_insert(s);//单词
}
scanf("%s",c);
_build();
_query(c);//文章
printf("%d\n",ans);
}
return 0;
}
标签:a long uil nbsp with 文章 main else should span
原文地址:http://www.cnblogs.com/hua-dong/p/7726311.html