Learned KMP, take this problem to practice practiced hand ... (But it seems a little overdone ...)
This is a water KMP template that matches several times, each time starting from the position after the last match, until the match fails.
Although the use of the algorithm "advanced" point, but incredibly slower than the violence of 40MS ah ah ah ...
Code:
1#include <iostream>2 using namespacestd;3 Const intp= the;4 Const ints=1000005;5 CharP[p],s[s];6 intNEXT[P],PL,SL;7 voidGetNext () {8next[0]=-1;9 intI=0, j=-1;Ten while(i<PL) { One if(j==-1|| s[i]==S[j]) { Ai++,j++; -next[i]=J; -}Else{ thej=Next[j]; - } - } - } + intKMP (intSt) { - inti=st,j=0; + while(i<sl&&j<PL) { A if(j==-1|| s[i]==P[j]) { ati++,j++; -}Else{ -j=Next[j]; - } - } - returnJ==pl? (I-J):-1; in } - intMain () to { +Freopen ("stat.in","R", stdin); -Freopen ("Stat.out","W", stdout); the inti,x,ans=0, flag=0, loc; * gets (p); $ gets (s);Panax NotoginsengPl=strlen (p); -Sl=strlen (s); the for(i=0; i<sl;i++) s[i]=ToLower (S[i]); + for(i=0; i<pl;i++) p[i]=ToLower (P[i]); A GetNext (); the for(X=KMP (0); x!=-1; X=KMP (x+PL)) { + if((x==0|| s[x-1]==' ') && (x+pl>=sl| | s[x+pl]==' ')){ - if(flag==0){ $flag=1; $Loc=x; - } -ans++; the } - }Wuyi if(flag) thecout<<ans<<' '<<Loc; - Else Wucout<<-1; - return 0; About}
NOIP2011 Universal group T2 Statistical Word number (STAT) KMP algorithm