KMP模板题 poj 3461 Oulipo

来源:互联网 发布:vmware 11 mac 破解版 编辑:程序博客网 时间:2024/05/08 14:27

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  1000005char 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;}