您的位置:首页 > 其它

HDOJ 2087 剪花布条(KMP)

2016-08-05 21:59 281 查看


剪花布条

Problem Description

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

 

Input

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

 

Output

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

 

Sample Input

abcde a3
aaaaaa aa
#

 

Sample Output

0
3

解题思路:KMP,记录匹配次数。

代码如下:

#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define EPS 1e-6
#define INF INT_MAX / 10
#define LL long long
#define MOD 100000000
#define PI acos(-1.0)

const int maxn = 1005;

char hbt[maxn],xst[maxn];
int next[maxn];
int lenhbt,lenxst;
int kmp()
{
memset(next,-1,sizeof(next));
next[1] = 0;
int cnt = 0;
for(int i = 2,j = 0;i <= lenxst;i++){
while(j > 0 && xst[j + 1] != xst[i])
j = next[j];
if(xst[j + 1] == xst[i])
j += 1;
next[i] = j;
}

for(int i = 1,j = 0;i <= lenhbt;i++){
while(j > 0 && xst[j + 1] != hbt[i])
j = next[j];
if(xst[j + 1] == hbt[i])
j += 1;
if(j == lenxst){
cnt++;
i += next[j];
}
}
return cnt;
}

int main()
{
while(scanf("%s",hbt + 1) != EOF && hbt[1] != '#'){
scanf("%s",xst + 1);
lenhbt = strlen(hbt + 1);
lenxst = strlen(xst + 1);
int ans = 0;
if(lenxst <= lenhbt)
ans = kmp();
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDOJ