HDU 1686 Oulipo

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

解题思路:简单的kmp算法。

 实现代码:

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

const int MAXN=1000010;
const int MAXM=10010;

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++;
        }
    }
    return ans;
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        char T[MAXN];
        char P[MAXM];
        int next[MAXM];
        scanf("%s",P);
        scanf("%s",T);
        int ans=kmp(T,P,next);
        printf("%d
",ans);
    }
}
原文地址:https://www.cnblogs.com/IKnowYou0/p/6652609.html