POJ-3461 Oulipo(KMP)

来源:互联网 发布:qq for linux ubuntu 编辑:程序博客网 时间:2024/06/05 18:08

题目链接:http://poj.org/problem?id=3461

题目大意:

给你两个字符串p和s,求出p在s中出现的次数。

思路:p在s中KMP匹配,匹配成功,再从next[last]的位置匹配即可,因为允许出现的两次有重叠的部分。

//1208 KB94 ms#include<cstdio>#include<iostream>#include<cstring>using namespace std;int n;char s[1000100],p[10100];int next[10100];void getnext(){    next[0]=-1;    int i=0,j=-1;    while(p[i]!=0){        while(j>-1&&p[i]!=p[j])            j=next[j];        j++;        i++;        next[i]=j;    }}int KMP(){    int i=0,j=0,ans=0;    while(s[i]!=0){        if(j==-1||s[i]==p[j]){            j++;            i++;            if(p[j]==0){                ans++;                j=next[j];            }        }        else j=next[j];    }    return ans;}int main(){    int _;    scanf("%d",&_);    while(_--){        scanf("%s%s",p,s);        getnext();        printf("%d\n",KMP());    }    return 0;}


0 0