hdu2087 剪花布条 KMP

剪花布条

一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢? 

Input

输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。 

Output

输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。 

Sample Input

abcde a3
aaaaaa  aa
#

Sample Output

0
3

思路:

也是一道kmp的板子题

代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1010;
char f[maxn],s[maxn];
int nxt[maxn];

void init(int m)
{
	int i = 1,j = 0;
	nxt[0] = 0;
	while (i < m)
	{
		if (s[i] == s[j])
			nxt[i ++] = ++ j;
		else if (!j)
			i ++;
		else
			j = nxt[j - 1];
	}
}
int kmp(int n,int m)
{
	int i = 0,j = 0,res = 0;
	while (i < n)
	{
		
		if (s[j] == f[i])
			i ++,j ++;
		else if (!j)
			i ++;
		else
			j = nxt[j - 1];
		if (j == m)
			j = 0,res ++;
	}
	return res;
}
int main()
{
	while (~scanf("%s",f) && strcmp(f,"#") != 0)
	{
		scanf("%s",s);
		int len = strlen(s),n = strlen(f);
		init(len);
		printf("%d\n",kmp(n,len));
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/cloudy_happy/article/details/81814311