kmp

#include<bits/stdc++.h>
using namespace std;
#define maxn 5000000
char a1[maxn],a2[maxn];int f[maxn];
void find(char* t,char* p,int *f)
{
    int n=strlen(t),m=strlen(p);
    int j=0;
    for (int i=0;i<n;i++)
    {
        while (j&&p[j]!=t[i]) j=f[j];
        if (p[j]==t[i]) j++;
        if (j==m) printf("%d\n",i-m+2); 
        //cout<<i-m+2<<endl; 
    }
};
void getfail(char *p,int *f)
{
    int m=strlen(p);
    f[0]=0;f[1]=0;
    for (int i=1;i<m;i++)
    {
        int j=f[i];
        while (j && p[i]!=p[j]) j=f[j];
        f[i+1]=p[i]==p[j]?j+1:0;
    }
};
int main()
{
    //std::ios::sync_with_stdio(false);
    freopen("noip.in","r",stdin);
    freopen("noip.out","w",stdout);
    //cin>>a1>>a2;
    scanf("%s",a1);
       scanf("%s",a2);
       int l=strlen(a2);
    getfail(a2,f);
    find(a1,a2,f);
    for (int i=1;i<=l;i++)
      printf("%d ",f[i]);
        //cout<<f[i]<<" ";
    return(0);
}

 

posted @ 2018-01-12 00:17  尹吴潇  阅读(134)  评论(0编辑  收藏  举报