洛谷P3375 kmp模板

题目链接

#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e6+10;
#define ll long long
vector<int>nxt,f;//f[i]表示匹配长度,nxt[i]表示前缀和后缀相等的个数,不包括最后一个
void get_next(string a){
    int n = a.size() - 1;
    nxt.resize(n+1);
    nxt[1] = 0;
    for(int i=2,j=0;i<=n;i++){
        while(j>0 && a[i]!=a[j+1])j = nxt[j];
        if(a[i]==a[j+1])
            j++;
        nxt[i] = j;
    }
}
void kmp(string a,string b){
    int n = a.size()-1,m = b.size() - 1;
    f.resize(m+1);
    for(int i=1,j=0;i<=m;i++){
        while(j>0 && (j==n || b[i]!=a[j+1]))j = nxt[j];
        if(b[i]==a[j+1]) j++;
        f[i] = j;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    string s;
    string sub;
    cin >> s;
    cin >> sub;
    s = " " + s;
    sub = " " + sub;
    int n = sub.size() - 1;
    int m = s.size() - 1;
    get_next(sub);
    kmp(sub,s);
    for(int i=1;i<=m;i++){
        if(f[i] == n){
            cout << i - n + 1 << '\n';
        }
    }
    for(int i=1;i<=n;i++){
        cout << nxt[i] << ' ';
    }
    return 0;
}
posted @ 2020-04-29 17:01  hh13579  阅读(101)  评论(0编辑  收藏  举报