KMP模板

题目链接:https://www.luogu.org/problemnew/show/P3375

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define P pair<int,int>
const int N=1e6+10;
const int mod=200907;
void read(int &a)
{
    a=0;
    int d=1;
    char ch;
    while(ch=getchar(),ch>'9'||ch<'0')
        if(ch=='-')
            d=-1;
    a=ch-'0';
    while(ch=getchar(),ch>='0'&&ch<='9')
        a=a*10+ch-'0';
    a*=d;
}
void write(int x)
{
    if(x<0)
        putchar(45),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
}
int kmp[N];
int main()
{
    string ss,st;
    cin>>ss>>st;
    int j=-1;
    kmp[0]=kmp[1]=-1;
    for(re int i=1;i<st.size();i++)
    {
        while(j>-1&&st[j+1]!=st[i])
            j=kmp[j];
        if(st[j+1]==st[i])
            j++;
        kmp[i]=j;
    }
    for(re int i=0;i<ss.size();i++)
    {
        while(j!=-1&&st[j+1]!=ss[i])
            j=kmp[j];
        if(ss[i]==st[j+1])
            j++;
        if(j==st.size()-1)
            cout<<i-st.size()+2<<endl,j=kmp[j];
    }
    for(re int i=0;i<st.size();i++)
        cout<<kmp[i]+1<<" ";
    return 0;
}

  

原文地址:https://www.cnblogs.com/acm1ruoji/p/10661722.html