hdu1686KMP
http://acm.hdu.edu.cn/showproblem.php?pid=1686
还是套模板。。。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1000000+10; char s1[maxn],s2[maxn]; int len1,len2,next[maxn]; void getnext() { int i=0,j=-1; next[0]=-1; while(i<len2) { if(j==-1||s2[i]==s2[j]) { i++,j++; next[i]=j; } else j=next[j]; } } int kmp() { int i=0,j=0,sum=0; while(i<len1&&j<len2) { if(j==-1||s1[i]==s2[j]) i++,j++; else j=next[j]; if(j==len2) { sum++; j=next[j]; } } return sum; } int main() { int t; scanf("%d",&t); while(t--) { scanf("%s%s",s2,s1); len1=strlen(s1); len2=strlen(s2); memset(next,0,sizeof(next)); getnext(); printf("%d\n",kmp()); } return 0; }

浙公网安备 33010602011771号