http://poj.org/problem?id=3461
纯KMP不多说上代码= =。。
View Code
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int pre[10005]; void predeal(char s[]) { int len,i,j; len = strlen(s); pre[0] = -1; j = -1; for(i = 1;i < len;i++) { while(j > -1 && s[j+1] != s[i]) j = pre[j]; if(s[j+1] == s[i]) j++; pre[i] = j; } } int kmp(char s1[],char s2[]) { int len1,len2,i,j,num; len1 = strlen(s1); len2 = strlen(s2); num = 0; for(i = 0,j = -1;i < len2;i++) { while(j > -1 && s1[j+1] != s2[i]) j = pre[j]; if(s1[j+1] == s2[i]) j++; if(j == len1-1) j = pre[j],num++; } return num; } int main() { int n,i,j; char s2[1000005],s1[10005]; scanf("%d",&n); while(n--) { memset(pre,0,sizeof(pre)); scanf("%s",s1); scanf("%s",s2); predeal(s1); int ans; ans = kmp(s1,s2); printf("%d\n",ans); } return 0; }