KMP的水题
需要注意的就是每当匹配成功了一个模式串时,必须要从模式串的0位置开始从新匹配。
根据题意,主串匹配成功的后,这一段就会被减去。所以在主串中该位置的前缀和后缀都没有,不能使用next数组预先比较。
由于该题的数据范围不大,我就用了两种方法,暴力和KMP。
原题
剪花布条
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10399 Accepted Submission(s): 6701
Problem Description
一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
Input
输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。
Output
输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。
Sample Input
abcde a3 aaaaaa aa #
Sample Output
0 3
暴力解法
#include<cstdio>
#include<cstring>
using namespace std;
#define EPS 1e-7
#define clr(x) memset(x, 0, sizeof(x))
#define long long ll
#define double db
#define PI acos(-1.0)
const int INF = 0x3f3f3f3f;
const int MOD=1000000007;
const int MAXN = 10000000;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
char str1[1005];
char str2[1005];
int ans;
int main()
{
while(1)
{
ans = 0;
scanf("%s", str1);
if(!strcmp(str1, "#"))
break;
scanf("%s", str2);
int n = strlen(str1);
int m = strlen(str2);
for(int i = 0; i < n; i++)
{
int flag = 1;
if(str1[i] == str2[0])
{
for(int j = 0, k = i; j < m && k < n; j++, k++)
{
//printf("%c %c\n", str1[k], str2[j]);
if(str1[k] != str2[j])
{
flag = 0;
break;
}
}
if(flag)
{
ans++;
i += m - 1;
}
}
}
printf("%d\n", ans);
}
return 0;
}
KMP解法
#include<cstdio>
#include<cstring>
using namespace std;
#define EPS 1e-7
#define clr(x) memset(x, 0, sizeof(x))
#define long long ll
#define double db
#define PI acos(-1.0)
const int INF = 0x3f3f3f3f;
const int MOD=1000000007;
const int MAXN = 1000000 + 5;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
int next[MAXN];
char str1[MAXN];
char str2[MAXN];
int ans;
void getnext(char x[], int m)
{
int i = 0, j = next[0] = -1;
while(i < m)
{
while(j != -1 && x[j] != x[i])
j = next[j];
next[++i] = ++j;
}
}
void kmp(char x[], char y[], int n, int m)
{
int i = 0, j = 0;
while(i < n)
{
while(j != -1 && x[j] != y[i])
j = next[j];
i++; j++;
if(j == m)
{
ans++;
j = 0;
}
}
}
int main()
{
while(1)
{
ans = 0;
scanf("%s", str2);
if(!strcmp(str2, "#"))
break;
scanf("%s", str1);
int n = strlen(str2);
int m = strlen(str1);
getnext(str1, m);
kmp(str1, str2, n, m);
printf("%d\n", ans);
}
return 0;
}