KMP(洛谷模板P3375)

· · 个人记录

写法比较诡异(比老师写的还诡异),代码很短,模板455B左右就能过。

警示自己:如果是多测,一定每次都要更新nxt数组。

#include <bits/stdc++.h>
using namespace std;
char s[1000005],p[1000005];
int nxt[1000005];
int main()
{
    cin >> s+1 >> p+1;
    int ls=strlen(s+1),lp=strlen(p+1);
    for (int j=1,i=0;j<lp;j++)
    {
        while(i&&p[i+1]!=p[j+1])i=nxt[i];
        if(p[i+1]==p[j+1])i++,nxt[j+1]=i;
    }
    for (int j=0,i=0;j<ls;j++)
    {
        while(i&&p[i+1]!=s[j+1])i=nxt[i];
        if(p[i+1]==s[j+1])i++;
        if(i==lp)cout << j-lp+2 << endl;
    }
    for (int i=1;i<=lp;i++)
    {
        cout << nxt[i] << " ";
    }
}