您的位置:首页 > 其它

HDU 1686 - Oulipo(kmp)

2015-10-21 20:59 375 查看

Problem link

分析:

kmp匹配


代码:

#include <cstdio>
#include <cstring>

const int maxn = 1000010;
char w[maxn], t[maxn];
int _next[maxn];

void get_next()
{
int w_len = strlen(w);
int i = 0, j;
_next[0] = j = -1;
while (i < w_len) {
if (j == -1 || w[j] == w[i]) {
i++;
j++;
_next[i] = j;
} else {
j = _next[j];
}
}
}

int get_times()
{
int ans = 0;
int w_len = strlen(w);
int t_len = strlen(t);
int i = 0, j = 0;
while (j < t_len) {
if (i == -1 || w[i] == t[j]) {
i++;
j++;
} else {
i = _next[i];
}
if (i == w_len) {
ans++;
i = _next[i];
}
}
return ans;
}

int main()
{
int T;
scanf("%d", &T);
while (T--) {
memset(w, 0, sizeof(w));
memset(t, 0, sizeof(t));
memset(_next, 0, sizeof(_next));
scanf("%s %s", w, t);
get_next();
printf("%d\n", get_times());
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: