HYSBZ 2565 最长双回文串(回文树)

博客介绍了如何使用回文树解决编程竞赛题目2565,通过正反遍历获取最长后缀和前缀,从而找到最长双回文串。文章提供了WA数据示例及解题思路,并包含关键代码实现。

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

题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2565


容易WA的数据:

Input

abccba

Output

5

解题思路:

利用回文树在插入字符的时候可以得知当前插入字符的最长回文后缀,我们用一个数组记录这个当前字符做结尾的后缀,正着跑一遍得到最长后缀,反着跑一遍相当于得到最长前缀,然后相邻前后缀相加的最大值就是答案。注意两个回文串长度都至少是一。

 

代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#include<map>
#include<set>

using namespace std;

#define ll long long
#define for1(i,a,b) for (int i=a;i<=b;i++)
#define for0(i,a,b) for (int i=a;i<b;i++)
#define rof1(i,a,b) for (int i=a;i>=b;i--)
#define rof0(i,a,b) for (int i=a;i>b;i--)
#define pb push_back
#define fi first
#define se second
#define debug(x) printf("----Line %s----\n",#x)
#define pt(x,y) printf("%s = %d\n",#x,y)
#define INF 0x3f3f3f3f
#define df(x) ll x;scanf("%I64d",&x)
#define df2(x,y) ll x,y;scanf("%I64d %I64d",&x,&y)
#define mod 1000000007
#define duozu(T) int T;scanf("%d",&T);while (T--)

const int N = 1e5+5;

const int maxn = 1e5+5;
const int ALP = 26;

char s[N];

struct PAM{ // 每个节点代表一个回文串
    int next[maxn][ALP]; // next指针,参照Trie树
    int fail[maxn]; // fail失配后缀链接
    int len[maxn]; // 回文串长度
    int s[maxn]; // 存放添加的字符
    int last; //指向上一个字符所在的节点,方便下一次add
    int n; // 已添加字符个数
    int p; // 节点个数
    int suf[maxn];//当前加入的字符最长回文后缀

    int newnode(int w){
        for(int i=0;i<ALP;i++)
            next[p][i] = 0;
        len[p] = w;
        return p++;
    }
    void init(){
        p = 0;
        newnode(0);
        newnode(-1);
        last = 0;
        n = 0;
        s[n] = -1; 
        fail[0] = 1;
    }
    int get_fail(int x){ 
        while(s[n-len[x]-1] != s[n]) x = fail[x];
        return x;
    }
    void add(int c){
        c -= 'a';
        s[++n] = c;
        int cur = get_fail(last);
        if(!next[cur][c]){
            int now = newnode(len[cur]+2);//len赋值在这
            fail[now] = next[get_fail(fail[cur])][c];
            next[cur][c] = now;
        }
        last = next[cur][c];
        suf[n] = len[last];
    }
}pam,ppam;


int main()
{
    //freopen("C:/Users/DELL/Desktop/input.txt", "r", stdin);
    //freopen("C:/Users/DELL/Desktop/output.txt", "w", stdout);
    scanf("%s",s);
    int len = strlen(s);
    pam.init();ppam.init();
    for0(i,0,len) pam.add(s[i]);
    rof1(i,len-1,0) ppam.add(s[i]);

    int ans = 0;

    for1(i,1,len-1)//遍历i=len不合法,后缀回文串为0了
        ans = max(pam.suf[i]+ppam.suf[len-i],ans);

    printf("%d\n",ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值