hihocoder 1015KMP

来源:互联网 发布:极端编程 编辑:程序博客网 时间:2024/05/11 02:54
#include <iostream>#include <algorithm>#include <stdio.h>#include <math.h>#include <string.h>using namespace std;#define N 2000010char s[N],p[N];int next1[N];int kmp(char* s, char* p){    int num=0;    int i = 0;    int j = 0;    int sLen = strlen(s);    int pLen = strlen(p);    while (i < sLen && j < pLen)    {        if (j == -1 || s[i] == p[j])        {            i++;            j++;        }        else        {            j = next1[j];        }        if(j==pLen) {            num++;            j = next1[j];        }    }    return num;}///求部分匹配表void GetKMPNext(char* p, int next[]){    int pLen = strlen(p);    next1[0] = -1;    int k = -1;    int j = 0;    while (j < pLen)  ///计算到0 - len    {        if (k == -1 || p[j] == p[k])        {            ++j;            ++k;            if (p[j] != p[k])                next1[j] = k;            else                next1[j] = next1[k];        }        else        {            k = next1[k];        }    }}int main() {    //freopen("input.txt","r",stdin);    int T;    scanf("%d",&T);    while(T--){        scanf("%s %s",p,s);  //p为模式串        GetKMPNext(p,next1);        printf("%d\n",kmp(s,p));    }    return 0;}
原创粉丝点击