当前位置: 代码迷 >> 综合 >> HOJ 2087 剪花布条(KMP,裸题)
  详细解决方案

HOJ 2087 剪花布条(KMP,裸题)

热度:56   发布时间:2024-02-06 17:20:45.0

KMP,裸题
本题要点:
1、先求出a字符串的next数组
2、再用b字符串和a数组来匹配,注意,每次匹配完成,就剪断对应的字符串,因此,
当 f[i] == n, 把 j 置零

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MaxN = 1010;
char a[MaxN], b[MaxN];
int Next[MaxN], f[MaxN];
int n, m;void calc_next()
{n = strlen(a + 1);Next[1] = 0;for(int i = 2, j = 0; i <= n; ++i){while(j > 0 && a[i] != a[j + 1])j = Next[j];if(a[i] == a[j + 1])++j;Next[i] = j;}
}void solve()
{int ans = 0;m = strlen(b + 1);for(int i = 1, j = 0; i <= m; ++i){while(j > 0 && b[i] != a[j + 1])j = Next[j];if(b[i] == a[j + 1])++j;f[i] = j;if(f[i] == n){++ans;j = 0;}}printf("%d\n", ans);
}int main()
{while(scanf("%s", b + 1) != EOF){if(b[1] == '#')break;scanf("%s", a + 1);calc_next();solve();}return 0;
}/* abcde a3 aaaaaa aa # *//* 0 3 */