题目信息:
Problem Description The 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:
Input The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
Output For 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 Input 3 BAPC BAPC AZA AZAZAZA VERDI AVERDXIVYERDIAN Sample Output 1 3 0 |
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
#define N 10005
using namespace std;
int Next[N],lenx,leny;
char T[N],S[100*N];
void get_next( ) {
int i,j;
i=0;
j=-1;
Next[0]=-1;
while(i<lenx) {
if(j==-1||T[i]==T[j]) {
++i;
++j;
if(T[i]!=T[j])
Next[i]=j;
else
Next[i]=Next[j];
} else
j=Next[j];
}
}
void KMP() {
int i=0;
int j=0;
int cnt=0;
get_next();
while(i<leny) {
if(j==-1||S[i]==T[j]) {
++i;
++j;
if(j==lenx)
++cnt;
} else
j=Next[j];
}
printf("%d\n",cnt);
}
int main() {
int t;
scanf("%d",&t);
getchar();
while(t--) {
gets(T);
gets(S);
lenx=strlen(T);
leny=strlen(S);
KMP();
}
}