Recently feel KMP not ah, used to be back board now to understand.
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <algorithm>5 using namespacestd;6 Const intmaxn=16000;7 8 CharS[MAXN];9 intK,p[maxn],ans;Ten One AInlinevoidKMP (Char*Str) - { - intj=0; the for(intI=2; str[i];i++) - { - while(str[j+1]!=str[i] && j) j=P[j]; - if(str[j+1]==str[i]) J + +; +p[i]=J; - } +j=0; A for(intI=1; str[i];i++) at { - while(str[j+1]!=str[i] && j) j=P[j]; - if(str[j+1]==str[i]) J + +; - while(j<<1>=i) j=P[j]; - if(j>=k) ans++; - } in } - intMain () to { +scanf"%s", s+1); -scanf"%d", &k); ans=0; the for(intI=0; s[i+1];i++) KMP (s+i); *printf"%d\n", Ans); $ return 0;Panax Notoginseng } -
Bzoj 3620
In fact, this is the meaning of the KMP P array, that is, S[1~p[i]]==s[i-p[i]+1~i], but the title of the required books can not be repeated, so that violence to find a p[p[i]] can be completed. N^2 violence can go through
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <algorithm>5 #defineLL Long Long6 using namespacestd;7 ConstLL maxn=1000100;8 ConstLL mod=1000000007;9 CharS[MAXN];Ten LL k,p[maxn],ans,cnt[maxn],kase; One A -InlinevoidKMP (Char*Str) - { theLL j=0; -cnt[1]=1; - for(LL i=2; str[i];i++) - { + while(str[j+1]!=str[i] && j) j=P[j]; - if(str[j+1]==str[i]) J + +; +p[i]=J; Acnt[i]=cnt[j]+1; at } - -j=0; LL Ret; - for(LL i=2; str[i];i++) - { - while(str[j+1]!=str[i] && j) j=P[j]; in if(str[j+1]==str[i]) J + +; - while(j<<1>i) j=P[j]; toAns= (ans* (cnt[j]+1))%Mod; + } - } the intMain () * { $scanf"%lld",&Kase);Panax Notoginseng for(LL kase=1; kase<=kase;kase++) - { thescanf"%s", s+1); +ans=1; KMP (S); Aprintf"%lld\n", Ans); the } + return 0; - } $
Bzoj 3670
In fact, the same as the previous one.
1#include <iostream>2#include <cstring>3#include <cstdio>4#include <algorithm>5 using namespacestd;6 7 Const intmaxn=1001000;8 CharS[MAXN],T[MAXN],STACK[MAXN];9 intLENS,LENT,P[MAXN],TOP,A[MAXN];Ten intMain () One { Ascanf"%s", s+1); -scanf"%s", t+1); -Lens=strlen (s+1), Lent=strlen (t+1); the intj=0; - for(intI=2; i<=lent;i++) - { - while(t[j+1]!=t[i] && j) j=P[j]; + if(t[j+1]==t[i]) J + +; -p[i]=J; + } Aj=0; at for(intI=1; i<=lens;i++) - { -J=a[top]; stack[++top]=S[i]; - while(t[j+1]!=stack[top] && j) j=P[j]; - if(t[j+1]==stack[top]) J + +; -a[top]=J; in if(j==lent) top-=Lent; - } to for(intI=1; i<=top;i++) Putchar (Stack[i]); +Putchar ('\ n'); - return 0; the } *
Bzoj 3942
Naked KMP.
Bzoj 3670 && bzoj 3620 && bzoj 3942 KMP