bzoj2565 最长双回文串(回文树)

本文介绍了一种使用两棵回文树来查找给定字符串中最长的双回文子串的方法。通过正反向建立回文树,分别求取前缀和后缀的回文子串,从而高效地解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

顺序和逆序读起来完全一样的串叫做回文串。比如acbca是回文串,而abc不是(abc的顺序为“abc”,逆序为“cba”,不相同)。
输入长度为n的串S,求S的最长双回文子串T,即可将T分为两部分X,Y,(|X|,|Y|≥1)且X和Y都是回文串。

分析:

正反建立两棵回文树分别求前缀和后缀即可。

代码:

#include <bits/stdc++.h>
using namespace std;
#define ms(a,b) memset(a,b,sizeof(a))
#define lson rt*2,l,(l+r)/2
#define rson rt*2+1,(l+r)/2+1,r
typedef unsigned long long ull;
typedef long long ll;
const int MAXN=3e5+5;
const double EPS=1e-8;
const int INF=0x3f3f3f3f;
const int MOD = 1e9+7;
struct palin_tree{
    int ch[MAXN][30], fail[MAXN], len[MAXN], last, tot, cnt[MAXN];
    palin_tree(){
        len[1] = -1;    tot = 1;    fail[0] = 1;
    }
    int insert(int c, int n, char *s){
        int x = last;
        while(s[n-1-len[x]] != s[n])    x = fail[x];
        if(!ch[x][c]){
            int v = ++tot, k = fail[x];
            len[v] = len[x] + 2;
            while(s[n-1-len[k]] != s[n])    k = fail[k];
            fail[v] = ch[k][c];
            ch[x][c] = v;
        }
        last = ch[x][c];
        cnt[last]++;
        return len[ch[x][c]];
    }
}t1,t2;
char s1[MAXN],s2[MAXN];
int n,len1[MAXN],len2[MAXN];
int main(){
    ios::sync_with_stdio(false);
    scanf("%s",s1+1);
    s1[0] = s2[0] = 0;
    int n = strlen(s1+1);
    for(int i=1;i<=n;i++){
        s2[i] = s1[n-i+1];
        len1[i] = t1.insert(s1[i]-'a',i,s1);
        len2[i] = t2.insert(s2[i]-'a',i,s2);
    }
    int ans = 0;
    for(int i=1;i<n;i++){
        ans = max(ans,len1[i]+len2[n-i]);
    }
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值