KMP algorithm
poj3461 Oulipo
Title: Template problem.
Idea: template problem.
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;intf[10010],ans;Chart1|10000],s2[1000000];voidprework () {intI,j,n; N=strlen (S1); f[0]=f[1]=0; for(i=1; i<n;++i) {j=F[i]; while(J&&s1[i]!=s1[j]) j=F[j]; F[i+1]= (s1[j]==s1[i]?j+1:0); }}voidWork () {intn,m,i,j; N=strlen (S1); m=strlen (S2); J=0; for(i=0; i<m;++i) { while(J&&s1[j]!=s2[i]) j=F[j]; if(S1[j]==s2[i]) + +J; if(j==n) + +ans; }}intMain () {intI,n; scanf ("%d",&N); for(i=1; i<=n;++i) {scanf ("%*c%s%*c%s",&s1,&S2); Prework (); Ans=0; work (); printf ("%d\n", ans); }}View Code
poj2752 seek the Name, seek the Fame
The main topic: to find a string prefix and suffix exactly the same length of all.
Idea: After maintaining the F-array, from the last loop, if the ch[j]==ch[f[j]],f[j]+1 is a workable length, j=f[j], keep looping. Suddenly found that the F array is magical. In fact, we can guarantee that the first f[j]+1 elements and the f[j]+1 elements ending with J must be equal.
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;Charch[400000];intf[400001]={0},ans[400001]={0},l;voidprework () {inti,j; f[0]=f[1]=0; for(i=1; i<l;++i) {j=F[i]; while(J&&ch[i]!=ch[j]) j=F[j]; F[i+1]= (ch[i]==ch[j]?j+1:0); }}voidWork () {intJ; J=l-1; while(j&&ch[j]==Ch[f[j]]) {ans[++ans[0]]=f[j]+1; J=F[j]; }}intMain () {intI,j,n; while(SCANF ("%s", &ch) = =1) {ans[0]=0; l=strlen (CH); ans[++ans[0]]=l; Prework (); Work (); for(i=ans[0];i;--i) printf ("%d", Ans[i]); printf ("\ n"); }}View Code
poj2406 Power Strings
The main idea: the substring repeats the most times and repeats exactly the length of the original string.
Idea: If you can repeat the length of the original string, then l% (L-f[l]) ==0, if you can ==0, then the answer is l/(l-f[l]), otherwise the answer is 1. This must be L and f[l], otherwise there will be a lot of strange problems ...
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;Charch[1000000];intf[1000001]={0},l;voidprework () {inti,j; f[0]=f[1]=0; for(i=1; i<l;++i) {j=F[i]; while(J&&ch[i]!=ch[j]) j=F[j]; F[i+1]= (ch[i]==ch[j]?j+1:0); }}intMain () {intI,j,ans; while(SCANF ("%s", &ch) = =1) {L=strlen (CH); if(ch[0]=='.') Break; Prework (); if(l% (l-f[l]) = =0) ans=l/(lF[l]); Elseans=1; printf ("%d\n", ans); }}View Code
KMP algorithm initially