poj3461 Oulipo

KMP的模版题。

#include<iostream>
#include<stdio.h>
#include<string.h>
#define MAXD 10001
using namespace std;
int N,q[MAXD],RES;
char T[MAXD*100],P[MAXD];

void PREFIX()
{
    int m=strlen(P);
    q[0]=-1;
    int k=-1;
    int i;
    for(i=1;i<m;i++)
    {
        while(k>=0&&P[k+1]!=P[i])
        k=q[k];
        if(P[k+1]==P[i])
        k++;
        q[i]=k;
    }
}

void KMP_MATCH()
{
    int n=strlen(T);
    int m=strlen(P);
    PREFIX();
    int t=-1;
    int i;
    for(i=0;i<n;i++)
    {
        while(t>=0&&P[t+1]!=T[i])
        {
            t=q[t];
        }
        if(P[t+1]==T[i])
        t++;
        if(t==m-1)
        RES++;
    }
}

int main()
{
    //freopen("test.txt","r",stdin);
    scanf("%d",&N);
    while(N--)
    {
        scanf("%s",P);
        scanf("%s",T);
        RES=0;
        KMP_MATCH();
        printf("%d\n",RES);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/longlongagocsu/p/2881149.html