EOJ #3441 唐纳德与子串 (Easy)【KMP】

来源:互联网 发布:2016年十大网络用语 编辑:程序博客网 时间:2024/06/15 10:41

题目链接

题目意思

给你一个文本串,然后给出Q次询问,每次给你两个数a,b和一个模式串,问你在区间【a,b】中有多少个模式串。

解题思路

简单的KMP算法。

代码部分

#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>#include <map>using namespace std;int nex[10001];void GetNext(string B){    int len_B=B.size();    nex[0]=-1;    int k = -1,j = 0 ;    while(j < len_B)    {        if(k == -1 || B[j] == B[k])        {            ++ k;            ++ j;            nex[j] = k;        }        else            k = nex[k];    }}int kmp(int a,int b,string A, string B){    int ans = 0, i = a, j = 0;    int len_B = B.size(), n = A.size();    while(i<=b)    {        if(j==-1||A[i] == B[j])        {            ++i;            ++j;        }        else            j = nex[j];        if(j == len_B)        {            ans++;            j = nex[j];        }    }    return ans;}int main(){    string a,b;    int l,r;    int n;    while(cin>>a)    {        scanf("%d",&n);        while(n--)        {            scanf("%d%d",&l,&r);            cin>>b;            GetNext(b);            int ans=kmp(l,r,a,b);            cout<<ans<<endl;        }    }    return 0;}
原创粉丝点击