HDU 1686 Oulipo(KMP变形求子串出现数目(可重))

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686

题目大意:给两个字符串A,B求出A中出现了几次B(计算重复部分)。

解题思路:稍微对kmp()函数进行修改,当j==m时,使得j=nxt[j]。类似地有HDU 2087题意相似,但是不计算重复部分,在j==m时,使j=0即可。

代码

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int N=1e6+5;
 7 
 8 int n,m;
 9 char s[N],p[N];
10 int nxt[N];
11 
12 void getnext(){
13     int i,j;
14     i=0,j=nxt[0]=-1;
15     while(i<m){
16         while(j!=-1&&p[i]!=p[j])
17             j=nxt[j];
18         nxt[++i]=++j;
19     }
20 }
21 
22 int kmp(){
23     getnext();
24     int i=0,j=0,n=strlen(s),ans=0;
25     while(i<n){
26         while(j!=-1&&s[i]!=p[j])
27             j=nxt[j];
28         i++,j++;
29         //修改
30         if(j==m){
31             ans++;
32             j=nxt[j];
33         }
34     }
35     return ans;
36 }
37 
38 int main(){
39     int t;
40     scanf("%d",&t);
41     while(t--){
42         scanf("%s%s",p,s);
43         n=strlen(s),m=strlen(p);
44         cout<<kmp()<<endl;
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/fu3638/p/8486455.html