P5496 【模板】回文自动机(PAM)

链接

题目链接

思路

裸题,没有思路,这里存个模板。

代码

#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 9;

namespace PAM
{
    int sz, tot, last;
    int cnt[maxn], ch[maxn][26], len[maxn], fail[maxn];
    char s[maxn];
    int newnode(int l)
    {
        sz++;
        memset(ch[sz], 0, sizeof(ch[sz]));
        len[sz] = l;
        fail[sz] = cnt[sz] = 0;
        return sz;
    }
    void clear()
    {
        sz = -1;
        last = tot = 0;
        s[tot] = '$';
        newnode(0);
        newnode(-1);
        fail[0] = 1;
    }
    int getfail(int x)
    {
        while (s[tot - len[x] - 1] != s[tot])
            x = fail[x];
        return x;
    }
    void insert(char c)
    {
        s[++tot] = c;
        int now = getfail(last);
        if (!ch[now][c - 'a'])
        {
            int x = newnode(len[now] + 2);
            fail[x] = ch[getfail(fail[now])][c - 'a'];
            ch[now][c - 'a'] = x;
        }
        last = ch[now][c - 'a'];
        //cnt[last]++;
    }
    int solve()
    {
        cnt[last] = cnt[fail[last]] + 1;
        return cnt[last];
    }
};
string s;
signed main()
{
    cin >> s;
    int tmp = 0;
    PAM::clear();
    for (int i = 0; i < s.length(); ++i)
    {
        if (i)
            s[i] = (s[i] - 97 + tmp) % 26 + 97;
        PAM::insert(s[i]);
        tmp = PAM::solve();
        cout << tmp << ' ';
    }
    cout << endl;
    return 0;
}
posted @ 2021-03-24 20:01  Theophania  阅读(66)  评论(0)    收藏  举报