Oulipo POJ - 3461(KMP)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define ll long long
#define inf 0x3f3f3f3f

using namespace std;
string b,a;
int T,nxt[10005],n1,n2;

void get_next()
{
    nxt[0]=-1;
    int i=0,j=-1;
    while(i<n2)
    {
        if(j==-1||b[i]==b[j])
        {
            i++;
            j++;
            nxt[i]=j;
        }
        else
            j=nxt[j];
    }
}
int kmp()
{
    int i=0,j=0,res=0;
    while(i<n1)
    {
        if(j==-1||a[i]==b[j])
        {
            i++;
            j++;
        }
        else
            j=nxt[j];
        if(j==n2)
        {
            res++;
            j=nxt[j];
        }
    }
    return res;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> T;
    while(T--)
    {
        cin >> b >> a;
        n1=a.size(),n2=b.size();
        get_next();
        cout << kmp() << endl;
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章