前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HYSBZ 2565 最长双回文串 (回文树)

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

作者头像
ShenduCC
发布2018-04-26 17:28:12
7750
发布2018-04-26 17:28:12
举报
文章被收录于专栏:算法修养算法修养

2565: 最长双回文串

Time Limit: 10 Sec  Memory Limit: 128 MB

Submit: 1377  Solved: 714

[Submit][Status][Discuss]

Description

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

Input

一行由小写英文字母组成的字符串S。

Output

一行一个整数,表示最长双回文子串的长度。

Sample Input

baacaabbacabb

Sample Output

12

利用回文树统计以i为结尾的最长回文串长度和以i为开始的最长回文串的长度

代码语言:javascript
复制
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <stdio.h>

using namespace std;
typedef long long int LL;
const int maxn=1e5+5;
char str[maxn];
struct Tree
{
    int next[maxn][26];
    int fail[maxn];
    int len[maxn];
    int s[maxn];
    int last;
    int p;
    int n;
    int new_node(int x)
    {
        memset(next[p],0,sizeof(next[p]));
        len[p]=x;
        return p++;
    }
    void init()
    {
        p=0;
        new_node(0);
        new_node(-1);
        last=0;n=0;
        s[0]=-1;
        fail[0]=1;
    }
    int get_fail(int x)
    {
        while(s[n-len[x]-1]!=s[n])
            x=fail[x];
		return x;
    }
    int add(int x)
    {
        x-='a';
        s[++n]=x;
        int cur=get_fail(last);
        if(!(last=next[cur][x]))
        {
            int now=new_node(len[cur]+2);
            fail[now]=next[get_fail(fail[cur])][x];
            next[cur][x]=now;
            last=now;
        }
        return len[last];
    }
}tree;
int s1[maxn];
int s2[maxn];
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        int len=strlen(str);
        tree.init();
        memset(s1,0,sizeof(s1));
        memset(s2,0,sizeof(s2));
        for(int i=0;i<len;i++)
        {
            s1[i]=tree.add(str[i]);
        }
        tree.init();
        for(int i=len-1;i>=0;i--)
        {
            s2[i]=tree.add(str[i]);
        }
        int ans=0;
        for(int i=0;i<len;i++)
        {
            ans=max(ans,s1[i]+s2[i+1]);
        }
        printf("%d\n",ans);
    }
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-05-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2565: 最长双回文串
  • Description
  • Input
  • Output
  • Sample Input
  • Sample Output
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档