【题目来源】
https://www.nowcoder.com/questionTerminal/1046cd038f7a4b04b2b77b415973de1c
http://acm.hdu.edu.cn/showproblem.php?pid=2087
【题目描述】
一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
【输入格式】
每组数据包含两个字符串s,t,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。
【输出格式】
对应每组输入,输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就输出0,每个结果占一行。
【算法分析】
在本文 KMP 函数的定义中,只需在 if(j==lent) 时,修改 j 的值,便可实现不重叠(j=0)及重叠(j=ne[j])计算模式串在主串中出现的次数。
题目“HDU 2087:剪花布条”,不重叠计算模式串在主串中出现的次数。(if(j==lent), j=0)
题目“HDU 1686:Oulipo”,重叠计算模式串在主串中出现的次数。(if(j==lent), j=ne[j])
【算法代码】
#include<iostream>
using namespace std;
const int maxn=1010;
int ne[maxn];
void getNext(string s) {
int len=s.length();
int i=0, j=-1;
ne[0]=-1;
while(i<len) {
if(j==-1 || s[i]==s[j]) {
i++;
j++;
ne[i]=j;
} else j=ne[j];
}
}
int KMP(string S,string T) {
int lens=S.length();
int lent=T.length();
int i=0;
int j=0;
int cnt=0;
while(i<lens && j<lent) {
if(j==-1 || S[i]==T[j]) {
i++;
j++;
} else j=ne[j];
if(j==lent) {
cnt++;
j=0;
}
}
return cnt;
}
int main() {
string S,T;
while(cin>>S && S[0]!='#') {
cin>>T;
getNext(T);
cout<<KMP(S,T)<<endl;
}
return 0;
}
/*
input:
abcde a3
aaaaaa aa
output:
0
3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/127112363
https://blog.csdn.net/hnjzsyjyj/article/details/127086502
https://blog.csdn.net/hnjzsyjyj/article/details/127105603