KMP

先贴一个讲的很好很详细的blog
http://blog.csdn.net/v_july_v/article/details/7041827

一道kmp的裸题
http://poj.org/problem?id=3461

#include<cstdio>
#include<cstring>
#define pb push_back 
#define mp make_pair
using namespace std;

const int maxn=1;
typedef long long ll;

int n,m,ans;
int next[10007];
char P[10007];
char W[1000007];

void getFail()
{
    int len=strlen(P),i,j,k;
    next[0]=-1;
    next[1]=0;
    for(i=1;i<len;++i)
    {
        j=next[i];
        while(j&&P[i]!=P[j]) j=next[j];
        if(P[i]==P[j]) next[i+1]=j+1;
        else next[i+1]=0;
    }
}

int find()
{
    int res=0;
    int len=strlen(W);
    int m=strlen(P);
    int i,j,k;
    j=0;
    for(i=0;i<len;++i)
    {
        while(j&&W[i]!=P[j]) j=next[j];
        if(W[i]==P[j]) j++;
        if(j==m)
        {
            res++;
            j=next[m];
        }
    }
    return res;
}

int main()
{
    int i,j,k,T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s%s",P,W);
        getFail();
        printf("%d\n",find());
    }

    return 0;
}

KMP的另一道版题:

// KMP
// http://hihocoder.com/contest/hiho3/problem/1
#include<cstdio>
#include<cstring>
using namespace std;

const int maxp=1e4+7,maxt=1e6+7;

char P[maxp],T[maxt];
int next[maxp];
int ch[maxp][257];

int ans,N;

void getfail()
{
    int i,j,k,len=strlen(P);
    next[0]=-1;
    next[1]=0;
    for(i=1;i<len;++i)
    {
        j=next[i];
        while(j!=-1&&P[j]!=P[i]) j=next[j];
        next[i+1]=j+1;
    }
    for(i=0;i<=len;++i)
    {
        for(j='A';j<='Z';++j)
        {
            if(j==P[i])
            {
                ch[i][j]=i;
                continue;
            }
            int c=next[i];
            while(c!=-1&&P[c]!=j) c=next[c];
            ch[i][j]=c;
        }
    }
}

void kmp()
{
    int i,j;
    int len=strlen(T);
    int m=strlen(P);
    j=0;
    for(i=0;i<len;++i)
    {
        j=ch[j][T[i]];
        j++;
        if(j==m)
        {
            ans++;
        }
    }
}

void doit()
{
    ans=0;
    scanf("%s%s",P,T);
    getfail();
    kmp();
    printf("%d\n",ans);
}


int main()
{
    int i,j,k;
    scanf("%d",&N);
    while(N--)
    {
        doit();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值