可持久化kmp

模板

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000100;
int n, m, q, nex[N], pre[N], top;
char s[N], t[N];
inline void add (char x) {
    int j = top;
    while (j && s[nex[j] + 1] != x) j = pre[j];
    s[++ top] = x;
    j = nex[j] + 1;
    if (top == 1) nex[top] = pre[top] = 0;
    else if (s[j] == x) {
        nex[top] = j;
        if (s[nex[j] + 1] == s[j + 1]) pre[top] = pre[j];
        else pre[top] = j;
    } else nex[top] = pre[top] = 0;
}
int main () {
    scanf("%s", t + 1);
    n = strlen(t + 1);
    for (int i = 1; i <= n; i ++) add(t[i]);
    scanf("%d", &q);
    while (q --) {
        scanf("%s", t + n + 1);
        m = strlen(t + n + 1);
        top = n;
        for (int i = n + 1; i <= n + m; i ++) {
            add(t[i]);
            printf("%d ", nex[i]);
        }
        printf("\n");
    }
    return 0;
}
posted @ 2022-08-28 23:09  duoluoluo  阅读(83)  评论(0)    收藏  举报