NOIP2011 Universal group T2 Statistical Word number (STAT) KMP algorithm

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.