2017-08-13 19:31:47
Writer:pprp
After a general understanding of the KMP algorithm, although not deep enough, but already can write code, (can be said to be back)
So this problem as a template, for everyone to use it.
To give you a substring p and a main string s, how many substrings in the main string?
The code is as follows: (I have marked the points to note, two functions can be used directly)
#include <iostream>#include<cstdio>#include<cstdlib>#include<cstring>using namespacestd;intans;Const intMAXN =1000005;intNEXT[MAXN];CharS[MAXN],P[MAXN];//construct next ArrayvoidGet_next () {inti =0 ; intj =-1; intLENP = strlen (P);//to use an extra variable, if written in the while loop, it will be tle .next[0] = -1; while(I <LENP) { if(j = =-1|| P[i] = =P[j]) {i++; J++; Next[i]=J; } ElseJ=Next[j]; }}//Start pattern matchingvoidKMP () {inti =0 ; intj =0 ; //to use an extra variable, if written in the while loop, it will be tle . intLENS =strlen (S); intLENP =strlen (P); Get_next (); //This construct cannot forget to write while(I < lens && J <LENP) { if(j = =-1|| P[J] = =S[i]) {i++; J++; } ElseJ=Next[j]; if(J = =LENP) {ans++; J=Next[j]; } }}intMain () {intCAs; CIN>>CAs; while(cas--) {ans=0; Memset (Next,0,sizeof(next)); scanf ("%s%s", P,s); KMP (); cout<< ans <<Endl; } return 0;}
POJ 3461-oulipo Classical KMP algorithm problem