KMP板子求调
查看原帖
KMP板子求调
158878
B1ade_楼主2022/10/29 11:21
//author:B1ade_
#include<bits/stdc++.h>
#define ll long long
#define il inline
#define MAXN 1000000+5
using namespace std;
char pa[MAXN],te[MAXN];
ll bor[MAXN],pan,ten;
il void pre_pattern()
{
    ll i=1,j=0;
    for (;i<pan;i)
    {
        if (pa[i]==pa[j])
        {
            bor[i]=j+1;
            ++j;
            ++i;
        }
        else
        if (j)
        {
            j=bor[j];
        }
        else
        {
            bor[i]=0;
            ++i;
        }
    }
}
il void kmp()
{
    ll i=0;//pointer used for the text
    ll j=0;//pointer used for the pattern
    while (i<ten&&j<pan)
    {
        if (te[i]==pa[j])
        {
            ++j;
            if (j==pan)
            {
                cout<<i<<'\n';
                j=bor[j-1];
            }
            ++i;
        }
        else
        if (j) j=bor[j-1];
        else ++i;
    }
}
int main()
{
    cin>>te>>pa;
    pan=strlen(pa);
    ten=strlen(te);
    pre_pattern();
    kmp();
    for (ll i=0;i<pan;++i) cout<<bor[i]<<" ";
    return 0;
}
//Ryuichi Sakamoto
//Please Be Well

10pts.

2022/10/29 11:21
加载中...