http://acm.hdu.edu.cn/showproblem.php?pid=1686
http://acm.hdu.edu.cn/showproblem.php?pid=2087
对于aaaaa aaa来说:
1686的答案就是2
2087的答案就是1
对于代码实现也只是微微的改动
1686代码:
#include <string>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char T[10010],S[1000010];
int next[10010];
void makenext(){
int i=0, j=-1;
next[0] = -1;
int len = strlen(T);
while(i < len){
if(j == -1 || T[i] == T[j]){
i++;
j++;
if(T[i] != T[j]) next[i] = j;
else next[i] = next[j];
}
else j = next[j];
}
return;
}
int KMP(){
int i=0, j=0, res=0;
int ls = strlen(S), lt = strlen(T);
while(i < ls){
if(j == -1 || S[i] == T[j]){
i++;
j++;
}
else j = next[j];
if(j >= lt){
res++;
j = next[j];
}
}
return res;
}
int main(){
int cas;
scanf("%d",&cas);
while(cas--){
scanf("%s%s",T,S);
makenext();
int ans = KMP();
printf("%d\n",ans);
}
return 0;
}
2087代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
char T[1010],S[1010];
int next[1010];
void getnext(){
int i=0, j = -1;
next[0] = -1;
int n = strlen(T);
while(i < n){
if(j == -1 || T[i] == T[j]){
i++, j++;
next[i] = j;
}
else j = next[j];
}
}
int KMP(){
int i = 0, j = 0, s = 0;
int LS = strlen(S), LT = strlen(T);
while(i < LS){
if(j == -1 || T[j] == S[i]){
i++;
j++;
}
else j = next[j];
if(j >= LT){
j = 0;
s++;
}
}
return s;
}
int main(){
while(scanf("%s%s",S,T) != EOF){
if(S[0] == '#') break;
getnext();
int ans = KMP();
printf("%d\n",ans);
}
//system("pause");
return 0;
}