[回文自动机]bzoj2342: [Shoi2011]双倍回文

题意:计算w wR w wR的最大长度
题解:构建出回文自动机,在fail树中dfs一遍即可。
时间复杂度: O(n)
空间复杂度: O(26n)

代码:

#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;
char s[501000];
int head[501000],ver[501000],nextt[501000],tot;
void add(int x,int y)
{
    tot++;
    nextt[tot]=head[x];
    head[x]=tot;
    ver[tot]=y;
}
int n;
struct data
{
    int len[501000],next[501000][26];
    int fail[501000],cnt,num[501000],last,tot;
    data()
    {
        len[0] = 0;len[1] = -1;fail[0] = 1;
        last = 0;cnt = 1;
    }
    void insert()
    {
        int l = n;
        for (int i = 1;i <= l;i++)
        {
            int t = s[i] - 'a';
            while (s[i - len[last] - 1] != s[i]) last = fail[last];
            if (!next[last][t])
            {
                cnt++;len[cnt] = len[last] + 2;
                int cur = fail[last];
                while (s[i-len[cur]-1]!=s[i]) cur = fail[cur];
                cur = next[cur][t];
                fail[cnt] = cur;
                next[last][t] = cnt;
            }
            last = next[last][t];
            num[last]++;
        }
    }
    void failtree()
    {
        add(1,0);
        for (int i = 2;i <= cnt;i++) add(fail[i],i);
    }
}par;

int num[501000],ans;
void dfs(int x)
{
    if (par.len[x] != -1)num[par.len[x]]++;
    if (par.len[x]%4==0 && num[par.len[x]/2]) ans = max(ans,par.len[x]);
    for (int i = head[x];i!=-1;i=nextt[i])
        dfs(ver[i]);
    if (par.len[x] != -1)num[par.len[x]]--;   
}
int main()
{
    int l;
    cin >> n;
    scanf("%s",s+1);
    s[0] = -1;
    par.insert();
    memset(head,-1,sizeof head);
    par.failtree();

    dfs(1);
    cout << ans <<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值