您的位置:首页 > 其它

KMP模板题 poj 3461 Oulipo

2013-08-18 15:26 495 查看
KMP算法理解链接:http://www.cppblog.com/oosky/archive/2006/07/06/9486.html

poj 3461 http://poj.org/problem?id=3461

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn  1000005
char t[maxn], p[maxn];
int next[maxn];
void getnext(char *s, int next[])
{
int len = strlen(s), j=0;
next[0] = next[1] = 0;
for (int i=1; i<len; i++)
{
j = next[i];
while (j && s[i]!=s[j])
j = next[j];
next[i+1] = s[i]==s[j] ? j+1 : 0;
}
//next数组是当文本串与匹配串失配的时候返回重新匹配的位置。
}
int kmp(char *t, char *p, int next[])
{
getnext(p, next);
int n = strlen(t), m = strlen(p), j = 0, cnt = 0;
for (int i=0; i<n; i++)
{
while (j && t[i]!=p[j])
j = next[j];
if (t[i]==p[j])
j++;
if (j==m)
cnt ++;//printf("%d ", i-m+1);//匹配成功的初始位置
}
return cnt;
}
int main()
{
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
scanf("%s%s", p, t);
printf("%d\n", kmp(t, p, next));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: