Problem DescriptionThe French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter 'e'. He was a member of the Oulipo group. A quote from the book:
InputThe first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
OutputFor every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T. Sample Input3 BAPC BAPC AZA AZAZAZA VERDI AVERDXIVYERDIAN Sample Output1 3 0
|
题目大意:
求在父串中有几个目标串,注意:在父串中上一个与目标串相同的子串可以和下一个与目标串相等的子串共用字符。
AC代码:
#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=10005;
const int maxn1=1000005;
char S[maxn1],T[maxn];
int l1,l2;
int next1[maxn];
void getnext()
{
int i=0,j=-1;
next1[0]=-1;
while(i<l2)
{
if(j==-1||T[i]==T[j])
{
++i;++j;
if(T[i]!=T[j])
next1[i]=j;
else
next1[i]=next1[j];
}
else
j=next1[j];
}
}
int kmp()
{
int i=0,j=0,t1=0;
while(i<=l1&&j<=l2)
{
if(j==-1||S[i]==T[j]){
++i;++j;
}
else
j=next1[j];
if(j==l2){ //注意这里是为什么
t1++;
j=next1[j];
}
}
return t1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
cin>>T>>S;
l1=strlen(S);
l2=strlen(T);
getnext();
cout<<kmp()<<endl;
}
return 0;
}
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686