[模板]kmp[poj3461][codevs5757]

来源:互联网 发布:无网络摄像头安装方法 编辑:程序博客网 时间:2024/06/07 02:50

codevs5757

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int MAXN = 1000000 + 50;char s1[MAXN],s2[MAXN];int next[MAXN];int n,m,ans;int main(){    scanf("%s",s1 + 1);    scanf("%s",s2 + 1);    n = strlen(s1 + 1);    m = strlen(s2 + 1);    for(int i = 2;i <= n;i ++){        int p = next[i - 1];        while(p && s1[p + 1] != s1[i])//失配,寻找最长前缀            p = next[p];        if(s1[p + 1] == s1[i])//            p ++;        next[i] = p;    }    int p = 0;    for(int i = 1;i <= m;i ++){        while(p && s1[p + 1] != s2[i])            p = next[p];        if(s1[p + 1] == s2[i])            p ++;        if(p == n)            ans ++;    }    printf("%d",ans);    return 0;}