HDU 2087 剪花布条

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2087

解题思路:

简单的kmp算法

实现代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN=1010;

void makeNext(const char P[],int next[]){
    int m=strlen(P);
    int k;
    memset(next,0,sizeof(next));
    for(int i=1,k=0;i<m;i++){
        if(k>0&&P[k]!=P[i])
            k=next[k-1];

        if(P[k]==P[i])
            k++;
        next[i]=k;
    }
}

int kmp(const char T[],const char P[],int next[]){
    int ans=0;
    makeNext(P,next);
    int m=strlen(P);
    int n=strlen(T);
    for(int i=0,k=0;i<n;i++){
        if(k>0&&P[k]!=T[i])
            k=next[k-1];

        if(P[k]==T[i])
            k++;
        if(k==m){
            ans++;
            k=0;
        }
    }
    return ans;
}

int main(){
    char T[MAXN];
    char P[MAXN];
    int next[MAXN];
    while(scanf("%s",T)!=EOF){
        if(T[0]=='#') break;
        scanf("%s",P);
        cout<<kmp(T,P,next)<<endl;
    }
}
原文地址:https://www.cnblogs.com/IKnowYou0/p/6652782.html