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:
Tout avait Pair normal, mais Tout s ' affirmait faux. Tout avait Fair normal, d ' Abord, puis surgissait l ' inhumain, l ' affolant. Il aurait voulu savoir oùs ' articulait l ' association qui l ' unissait au roman:stir son tapis, Assaillantàtout instant s On imagination, l ' intuition d ' un tabou, la vision d ' un mal obscur, d ' un quoi vacant, d ' UN non-dit:la vision, l ' avision D ' Un oubli commandant tout, oùs ' abolissait la raison:tout avait l ' air normal mais ...
Perec would probably has scored high (or rather, low) in the following contest. People is asked to write a perhaps even meaningful text on some subject with as few occurrences of a given "word" as poss Ible. Our tasks are to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the Competit Ors. These competitors often write very long texts with nonsense meaning; A sequence of 500,000 consecutive ' T ' is not unusual. And they never use spaces.
So we want to quickly find out what often a word, i.e., a given string, occurs in a text. More Formally:given the alphabet {' A ', ' B ', ' C ', ..., ' Z '} and both finite strings over that alphabet, a word W and a text T , count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. occurrences may overlap.
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:
One line with the word W, a string over {' A ', ' B ', ' C ', ..., ' Z '}, with 1≤| w| ≤10,000 (Here | w| Denotes the length of the string W).
One line with the text T, a string over {' A ', ' B ', ' C ', ..., ' Z '}, with | w| ≤| T| ≤1,000,000.
Outputfor every test case in the input file, the output should contain a single number, on a single line:the number of OC Currences of the word W in the text T.
Sample Input
3BAPCBAPCAZAAZAZAZAVERDIAVERDXIVYERDIAN
Sample Output
130
Source
KMP templates
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace STD; #define N 1000005char a[n],b[n];int ans,next[n];void getfail (char *b) {int i,j;int len=strlen (b); next[0]=-1;i=0;j=- 1;while (I<len) {if (j==-1| | B[i]==b[j]) {i++;j++;next[i]=j;} ELSEJ=NEXT[J];}} void Kmp (char *a,char *b) {int i,j;int lena=strlen (a); int Lenb=strlen (b); I=j=0;while (I<lena) {if (j==-1| | A[i]==b[j]) {i++;j++;} Elsej=next[j];if (J==LENB) {ans++;j=next[j];}}} int main () {int i,j,t;scanf ("%d", &t), while (t--) {scanf ("%s%s", B,a), Getfail (b); ANS=0;KMP (A, a);p rintf ("%d\n", ans );} return 0;}
HDU 1686 Oulipo (KMP)